javascript 将样式附加到 DOM 不替换现有的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3723415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:02:39  来源:igfitidea点击:

Append Style to DOM not Replacing Existing

javascriptcssdomjavascript-events

提问by Codex73

How can I appendstyle element to DOM without eliminating existing style on the item (eg color, text-align, etc)?

如何在不消除项目现有样式(例如颜色、文本对齐等)的情况下样式元素附加到 DOM?

The event calls the function, but the problem is 'Style' gets completely replaced with the single item instead.

该事件调用了该函数,但问题是“样式”完全替换为单个项目。

I have simple code triggered on the event:

我在事件上触发了简单的代码:

function changeback(onoff) {
   if(onoff) {
      document.getElementById("field1").style.background="#fff";
   } else            
      document.getElementById("field1").style.background="#000";
}

回答by AaronM

Which browser are you using? In Chrome, this works for me:

您使用的是哪个浏览器?在 Chrome 中,这对我有用:

<html> 
<head> 
<style type="text/css"> 
  .test { background: #ff0000; font-family: "Verdana"; }
</style> 
<script type="text/javascript"> 
  function changeback(onoff)
  {
    if(onoff){
      document.getElementById("field1").style.background="#0f0";
    } else {
      document.getElementById("field1").style.background="#000";
    }
  }
 </script> 
 </head> 
 <body> 
   <h1>Test</h1> 
   <p id="field1" onclick="changeback(true);" class="test">This is a test</p> 
</body> 
</html> 

When I click on the text, the background color changes, but the rest of the style (in this case, the font) stays the same.

当我单击文本时,背景颜色会发生变化,但其余的样式(在本例中为字体)保持不变。

Is that what you're trying to do?

这就是你想要做的吗?

回答by Rajat

Here is how you can do it :

您可以这样做:

var elem = document.getElementById('YOUR ELEMENT ID');
elem.style.setProperty('border','1px solid black','');

elem.styleis an object implementing the CSSStyleDeclarationinterface which supports a setPropertyfunction. If you check the style property in Firebug now, you will notice addition of the border property within the style attribute of the element.

elem.style是一个实现CSSStyleDeclaration接口的对象,该接口支持一个setProperty函数。如果您现在检查 Firebug 中的 style 属性,您会注意到在元素的 style 属性中添加了边框属性。