我正在尝试根据一个类是否包含特定文本来设置与其他类(具有相同类名)不同的样式。我已经设法添加类,但我现在面临的问题是主 css 类正在否决它。要显示的代码:
HTML
<div id="master">
<div>
<div class="attributes">
<a href="#">Not important</a>
</div>
</div>
<div>
<div class="attributes">
<a href="#">Not important</a>
</div>
</div>
<div>
<div class="attributes">
<a href="#">Important Text and Other Stuff</a>
</div>
</div>
<div>
<div class="attributes">
<a href="#">Not important</a>
</div>
</div>
</div>
原始 CSS
#master div.attributes {
float: left;
font-size: 12px;
margin-top: 0px !important;
width: 330px;
clear: both;
}
.attributes {
color: #58585a !important;
font-size: 14px;
margin: -10px 0 0 !important;
}
使用 jQuery
$('div.attributes:contains("Important Text")').addClass('attributes2');
添加了 CSS
.attributes2
{
clear: none;
float: right;
font-size: 12px;
margin-top: 0;
width: 330px;
}
因此它成功添加了 .attributes2 并使用了它,但是 #master div.attributes css 类否决了它。任何人都可以想办法解决这个问题吗?我已经进行了无数次谷歌和堆栈搜索,没有运气......我应该提一下我没有能力编辑 HTML id 和类名。但我可以编辑 css 和 jQuery。
非常感谢。
最佳答案
这是因为 id #master
比类 .attributes2
有更高的优先级,它有更多 specificity .因此,要解决此问题,您只需向 .attributes2
block 添加更多特异性:
#master div.attributes2 {
...
}
另请注意,您应该对 .attributes
block 做同样的事情,而不是使用 !important
规则,因为 !important
规则打断了 CSS 的级联特性,使代码更难维护。
关于jquery - 尽管名称重复,但强制 div 类对 jQuery 使用不同的 css 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44307017/