我有一个带有单个子项的 HTML 标记,每个子项都有自己的样式。
<div style="font-size:12px;color:red">
<div style="color:blue">...</div>
</div>
我想合并这两个标签而不改变结果。我的意思是子样式必须打败父样式。在这种情况下,结果必须是:
<div style="font-size:12px;color:blue">...</div>
我该怎么做?
编辑:
我有两个 cssText,我想将它们合并到一个字符串中以将它们作为样式属性。
在上面的例子中,我有
var st1=font-size:12px;color:red;
和 var st2=color:blue;
我想优先合并 st1 和 st2。
最佳答案
html
<div id=parent style="font-size:12px; color:red">
<div id="child" style="color:blue">text</div>
</div>
我添加 ID 只是为了方便抓取这些元素,还有很多其他方法可以做到这一点。
这是 JS
parentClass = document.getElementById("parent").style.cssText;
childClass = document.getElementById("child").style.cssText;
document.getElementById("parent").style.cssText = parentClass+childClass;
以非常容易理解的风格编写代码。现在父元素将同时具有父类和子类。如果任何类重复,那么将应用子类的样式,因为它是最后编写的(这就是 CSS 的工作原理)。
最后,如果你愿意,你可以使用 removeChild() 移除子元素。
关于jquery - 如何合并两个div样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42207377/