Append Style to DOM not Replacing Existing

时间秒杀一切 提交于 2020-02-23 00:46:02

问题


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

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";
}

回答1:


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

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




回答2:


Here is how you can do it :

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

elem.style is an object implementing the CSSStyleDeclaration interface which supports a setProperty function. If you check the style property in Firebug now, you will notice addition of the border property within the style attribute of the element.



来源:https://stackoverflow.com/questions/3723415/append-style-to-dom-not-replacing-existing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!