Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 添加CSS但保持内联样式_Javascript_Css - Fatal编程技术网

Javascript 添加CSS但保持内联样式

Javascript 添加CSS但保持内联样式,javascript,css,Javascript,Css,我做错了什么 需要用JavaScript添加CSS,但我必须保留所有内联样式 在这种情况下,当用户单击h1元素时,内联样式的颜色需要保持不变,只需从javascript添加新样式即可 这是小提琴: 测试 试验 函数some(){ var元素=document.querySelectorAll('h1'); 元素。forEach(功能(项){ item.onclick=函数(){ var inlineCss=this.style; item.style.cssText=inlineCss+'背景:

我做错了什么

需要用JavaScript添加CSS,但我必须保留所有内联样式

在这种情况下,当用户单击h1元素时,内联样式的颜色需要保持不变,只需从javascript添加新样式即可

这是小提琴:

测试
试验
函数some(){
var元素=document.querySelectorAll('h1');
元素。forEach(功能(项){
item.onclick=函数(){
var inlineCss=this.style;
item.style.cssText=inlineCss+'背景:蓝色;字体大小:12px;';
}
});
}
一些();

您需要使用
style.background
style.fontSize
javascript属性:

功能部分(el){
var元素=document.querySelectorAll('h1');
元素。forEach(功能(项){
item.onclick=函数(){
item.style.background='blue';//更改元素的背景
item.style.fontSize='12px';//更改元素的字体大小
}
});
}
一些()
测试

测试此样式。样式不是文本,而是对象。您必须首先自己使用调试器为什么不使用
+=
而不是
=
<h1 style="color: red;">Test</h1>
<h1 style="color: green;">Test</h1>

<script>
function some(){
    var element = document.querySelectorAll('h1');

      element.forEach(function(item){

        item.onclick = function(){
            var inlineCss = this.style;

                item.style.cssText = inlineCss + 'background: blue; font-size: 12px;';
          }

      });
}

some();

</script>