[英]Class selector priority over several unique ID's
I have three unique ID's like so: 我有三个像这样的唯一ID:
#green-text {
color: #57BF90;
}
#grey-text {
color: #474444;
}
#orange-text {
color: #FFAC00;
}
Which each has a class called .example-button
. 每个都有一个名为
.example-button
的类。 When one of these classes is clicked, I'd like to use jQuery to do 当单击这些类之一时,我想使用jQuery做
$('.example-button').click(function() {
$(this).addClass('white-text');
$(this).siblings().removeClass('white-text');
}
where 哪里
.white-text {
color: white;
}
But of course this class doesn't take priority over the ID's so nothing would change. 但是,当然,此类并不比ID优先,因此不会发生任何变化。 Is there a better way to script this other than
有没有比这更好的脚本编写方法了
.white-up-text#green-text {
color: white;
}
.white-up-text#grey-text {
color: white;
}
.white-up-text#orange-text {
color: white;
}
or other than using !important
? 还是除了使用
!important
? (I'm avoiding !important
in order to respect good CSS practice) (为了避免遵守良好的CSS惯例,我避免使用
!important
)
Absolutely, you can keep nesting your styles in order to increase the specificity and target the element. 绝对可以,您可以继续嵌套样式,以提高特异性和针对性。
You could use !important
but that should be a last option. 您可以使用
!important
但这应该是最后的选择。 Otherwise your code will not be scalable after a certain point and is considered a worst practice. 否则,您的代码在特定点后将无法扩展,这被认为是最糟糕的做法。
And put, id's first since they carry more weight (Just a pattern which in no way affects specificity) 而且,id是第一个,因为它们具有更大的重量(只是一种模式,绝不会影响特异性)
#green-text.white-text {
color: white;
}
Once you associate a style to an id. 将样式与ID关联后。
In the long run it won't be maintainable. 从长远来看,它将无法维护。 So it is always a better idea to replace it with a
class
instead 所以用一个
class
代替它总是一个更好的主意
.green-text.white-up-text {
color: white;
}
.grey-text.white-up-text {
color: white;
}
.orange-text.white-up-text {
color: white;
}
Also take a look at OOCSS which advocates the principle of code reuse, where classes are the king. 还可以看看OOCSS ,它倡导代码重用原理,其中类为王。
Change your jquery to : 将您的jquery更改为:
$('.example-button').click(function() {
$(this).css("color","white");
$(this).siblings().removeAttr('style'); });
This works as inline style has greater specificity than id selector. 这是因为内联样式比id选择器更具特异性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.