问题
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
回答1:
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.
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
回答2:
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:
.dibHighlight{border:1px solid orange !important;}
回答3:
The class below does not work because there is some existing class whose code is below this class in your css file.
.dibHighlight{border:1px solid orange;}
to make below code work just paste the above css code in the last line of your css file.
$(this).closest('.drop').addClass('dibHighlight');
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 of addClass()
because even toggleClass()
works as an addClass()
in case the class you want to add does not already exists.
来源:https://stackoverflow.com/questions/5394366/does-addclass-in-jquery-override-any-existing-css-class-based-styles