JQuery 中的 addClass 是否会覆盖任何现有的基于 css 类的样式?
我正在尝试向单击的元素添加一个类。这些元素已分配有多个类,其中包括带有边框的类。
虽然我知道我可以使用removeClass()删除当前的CSS类,但我需要该类提供的其他样式。所以我想知道以下示例是否可以不使用 addClass() 覆盖边框样式,边框是否已经设置了属性?我不想使用内联样式,因为它们不太容易维护。
CSS:
.dibHighlight{border:1px solid orange;}
不起作用的 JQuery:
$(this).closest('.drop').addClass('dibHighlight'); // Doesn't work
起作用的 JQuery:
$(this).closest('.drop').css({ border: "1px solid orange" }); // Works
I'm trying to add a class to elements clicked on. The elements have several clases already assigned to them including one with a border.
Although I know I can remove a current CSS class using removeClass() I need other styles that the class provides. So what I wonder is given the following examples can I not override a border style with addClass() is that border has a property already set? I don't want to use inline styles as they are not as easy to maintain.
CSS:
.dibHighlight{border:1px solid orange;}
JQuery that doesn't work:
$(this).closest('.drop').addClass('dibHighlight'); // Doesn't work
JQuery that works:
$(this).closest('.drop').css({ border: "1px solid orange" }); // Works
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以根据 CSS 特异性 的规则,使用
addClass
覆盖其他类,就像 CSS 类一样在元素上使用class
属性时,会覆盖/继承彼此的属性。第二个示例之所以有效,是因为它相当于在元素上设置
style
属性,根据 CSS 特异性,该属性几乎是最具体的。相反,第一个示例不起作用,因为可能有一个比
.dibHighlight
更具体的 CSS 类You can override other classes using
addClass
according to the rules of CSS specificity just as CSS classes override/inherit properties from each other when using theclass
attribute on the element.The reason your second example works, is because it is equivalent to setting the
style
attribute on the element which is pretty much the most specific according to CSS specificity.Conversely, the first example doesn't work because there is probably a CSS class that is more specific then
.dibHighlight
可能还有另一个类的优先级高于 CSS 中其他位置定义的
dibHighlight
。您应该使用 Firebug(或类似的开发工具)测试哪些样式/类应用于您的元素。或者对于脏的快速修复,请尝试以下操作:
There is probably another class that takes priority over
dibHighlight
defined somewhere else in your CSS. You should test which styles/classes are applied to your element using Firebug (or similar developer tools).Or for the dirty quick fix, try this:
下面的类不起作用,因为有一些现有类的代码位于您的 css 文件中该类的下面。
要使下面的代码工作,只需将上面的CSS代码粘贴到CSS文件的最后一行。
执行此操作后,当您在jquery中使用addClass添加类dibHighlight时,它将覆盖现有的类相似属性。
我建议使用
toggleClass()
而不是addClass()
因为即使toggleClass()
也可以用作addClass()
如果您要添加的类尚不存在。The class below does not work because there is some existing class whose code is below this class in your css file.
to make below code work just paste the above css code in the last line of your css file.
After doing this when you will add class dibHighlight with addClass in jquery it will override the existing class similar attribute.
I suggest using
toggleClass()
instead ofaddClass()
because eventoggleClass()
works as anaddClass()
in case the class you want to add does not already exists.