gpt4 book ai didi

javascript - 类选择器优先于多个唯一 ID

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:48 27 4
gpt4 key购买 nike

我有三个唯一的 ID,如下所示:

#green-text {
color: #57BF90;
}

#grey-text {
color: #474444;
}

#orange-text {
color: #FFAC00;
}

每个都有一个名为 .example-button 的类。单击其中一个类时,我想使用 jQuery 来做

$('.example-button').click(function() {
$(this).addClass('white-text');
$(this).siblings().removeClass('white-text');
}

在哪里

.white-text {
color: white;
}

但是当然这个类不会优先于 ID,所以什么都不会改变。除了

之外,还有更好的脚本编写方法吗
.white-up-text#green-text {
color: white;
}
.white-up-text#grey-text {
color: white;
}
.white-up-text#orange-text {
color: white;
}

或者除了使用 !important 之外? (为了尊重良好的 CSS 实践,我避免使用 !important)

最佳答案

当然,您可以继续嵌套您的样式以增加特异性并定位元素。

您可以使用 !important 但这应该是最后的选择。否则,您的代码在某个时间点后将无法扩展,这被认为是最糟糕的做法。

而且,id 是第一个,因为它们具有更大的权重(只是一种绝不会影响特异性的模式)

#green-text.white-text {
color: white;
}

一旦您将样式与 ID 相关联。

  • 覆盖的唯一方法是使用 !important(避免使用)
  • 使用更具体的样式(它总是嵌套在 id 中,所以你的目标是它)。
  • 使用比 id 更明确的内联样式

从长远来看,它将无法维护。所以用 class 代替它总是一个更好的主意

.green-text.white-up-text {
color: white;
}
.grey-text.white-up-text {
color: white;
}
.orange-text.white-up-text {
color: white;
}

另请参阅 OOCSS 提倡代码复用原则,类为王。

关于javascript - 类选择器优先于多个唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38486618/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com