jquery - 如何合并两个div样式?

标签 jquery html css

我有一个带有单个子项的 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/

相关文章:

javascript - 仅在使用 jquery 从末尾删除后添加

javascript - 在所有元素顶部显示全屏不确定进度条

javascript - 为什么我尝试使用 document.stylesheets 不起作用?

html - Bootstrap 使用固定的导航栏和 anchor 标记跳转到部分

javascript - Jquery SlideDown 偶尔工作

html - 如何正确标记/设置有序列表的样式以补偿大元素编号

javascript - 根据一天中的时间更改哪个表行背景颜色

jquery - jQuery 模板中的多个测试条件 "if"

javascript - 检查常见下拉项(JavaScript、jQuery)

javascript - Asp.Net MVC 中的 Accordion 使用 html、css 和 JS