有很多关于相关主题的讨论,但没有针对这个具体问题。所以,请不要在没有仔细阅读问题的情况下跳转并将其标记为重复。
JQuery 没有任何修改类的方法(尽管它有添加和删除类的方法)。对此有很多讨论。我的问题是假设有一个类
.myclass
{
property1: value1;
property2: value2;
...
}
然后,我动态地使用 JQuery 执行如下操作:
newstyle = "<style type='text/css'>.myclass {property1:newvalue1; property2: newvalue2,...} </style>";
$('head').append(newstyle);
如有错别字请见谅。我的问题是:
问题一:动态定义的类似乎覆盖了静态定义的myclass。在某种程度上,这不是动态类修改吗?这有什么不是跨浏览器或任何其他陷阱的吗?
问题2:是否覆盖或补充了静态定义的myclass?我的意思是,如果静态定义的 myclass 有 property1 和其他属性,而动态定义的 myclass 只有 property 2 会怎么样。现在定义的总属性是否会被动态定义的类覆盖并具有交集的两个类的联合?
是的,我尝试过并得到了不同的行为,但我没有基础知道应该期待什么。
最佳答案
这是由 specificity 引起的.您动态添加的样式将覆盖您现有的样式,因为您的动态 CSS 在您的非动态 CSS 之后呈现:
<!-- static style element -->
<style type="text/css">
.myclass {
property1: value1;
}
</style>
<!-- dynamic style element -->
<style type="text/css">
.myclass {
property1: value2; /* Same specificity, overrides previous. */
}
</style>
我创建了一个 this JSFiddle demo来证明这一点。这里我有一个 ID 为“example”的 figure
元素。有一个将 background
属性设置为红色的 figure
选择器和一个将 color
设置为 figure#example
选择器属性为白色。然后,我像您所做的那样附加一个 CSS style
元素,它使用 figure
选择器将 background
属性更改为绿色,并尝试更改color
属性为黑色。
由于 figure#example
选择器比动态 figure
选择器具有更高的特异性,因此仅更改了 background
属性。
<!-- static style element -->
<style type="text/css">
.myclass.myclass { /* Higher specificity selector by duplicating class. */
property1: value1;
}
</style>
<!-- dynamic style element -->
<style type="text/css">
.myclass {
property1: value2; /* No change as previous has higher specificity. */
}
</style>
如果我们prepend 这个 CSS,动态 CSS 被添加在我们的静态 CSS 之前,并且我们的静态 CSS 被使用,因为我们的选择器的特性是相同的。 JSFiddle prepend demo :
<!-- dynamic style element -->
<style type="text/css">
.myclass {
property1: value1;
}
</style>
<!-- static style element -->
<style type="text/css">
.myclass {
property1: value2; /* Same specificity, overrides previous. */
}
</style>
关于jquery - 使用 JQuery 方法覆盖类以插入样式元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20881471/