简体   繁体   English

添加 CSS 但保持内联样式

[英]Add CSS but keep inline style

What I'm doing wrong.我做错了什么。

Need to add CSS with JavaScript but I have to keep all the inline styles.需要使用 JavaScript 添加 CSS,但我必须保留所有内联样式。

In this case when user clicks h1 element, the color of the inline style needs to stay the same and just add new style from javascript.在这种情况下,当用户单击 h1 元素时,内联样式的颜色需要保持不变,只需从 javascript 添加新样式即可。

Here is fiddle: https://jsfiddle.net/59qfxwcu/这是小提琴: https : //jsfiddle.net/59qfxwcu/

<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>

You need to use style.background and style.fontSize javascript properties:您需要使用style.backgroundstyle.fontSize javascript 属性:

 function some(el) { var element = document.querySelectorAll('h1'); element.forEach(function(item) { item.onclick = function() { item.style.background = 'blue'; // Change the background of the element item.style.fontSize = '12px'; // Change the font-size of the element } }); } some();
 <h1 style="color: red;">Test</h1> <h1 style="color: green;">Test</h1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM