JQuery中的addClass是否会覆盖任何现有的基于CSS类的样式? [英] Does addClass in JQuery override any existing css class based styles?

查看:776
本文介绍了JQuery中的addClass是否会覆盖任何现有的基于CSS类的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为单击的元素添加一个类.这些元素已经分配了几类,其中一个带有边框.

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.

尽管我知道我可以使用removeClass()删除当前的CSS类,但我需要该类提供的其他样式.所以我想知道以下示例,我不能用addClass()覆盖边框样式是,边框已经设置了属性吗?我不想使用内联样式,因为它们不易维护.

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:

JQuery that doesn't work:

$(this).closest('.drop').addClass('dibHighlight'); // Doesn't work

有效的jQuery:

$(this).closest('.drop').css({ border: "1px solid orange" }); // Works

推荐答案

您可以根据

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 the class attribute on the element.

您的第二个示例起作用的原因是,因为它等效于在元素上设置style属性,根据CSS的特定性,该属性几乎是最特定的.

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.

相反,第一个示例不起作用,因为可能有一个CSS类比.dibHighlight

Conversely, the first example doesn't work because there is probably a CSS class that is more specific then .dibHighlight

这篇关于JQuery中的addClass是否会覆盖任何现有的基于CSS类的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆