将样式附加到DOM而不是替换现有的样式 [英] Append Style to DOM not Replacing Existing

查看:107
本文介绍了将样式附加到DOM而不是替换现有的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

该事件调用该函数,但问题是'Style'完全被替换为单个项目。

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


推荐答案

您使用的是哪种浏览器?在Chrome中,这适用于我:

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.

这是你想要做的吗?

这篇关于将样式附加到DOM而不是替换现有的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆