jQuery .addClass has no effect
fellow coders, just came across a strange (at least to me) behaviour for the .addClass method. I'm trying to highlight an item (div) when the mouse hovers over it by using the .addClass method and a .highlight class that changes the background-color of the div. (i'm using jQuery instead of the css :hover method for a reason.)
The code works meaning, the .highlight class is added to the div however the color is not changing. the color will only change when the div's default css class does NOT have background-color defined in it. in other words, if the div is defined with a class that includes say background-color: white; the .highlight class is added but the color does not change.
Is this normal or am I missing something? for now, i'm using .css('background-color', ....) to get the highlight going but i'm curious as to why the .addClass method is not wo开发者_如何学Pythonrking.
thanks.
Your original CSS class is overriding the new one.
You can prevent this by adding !important
to the hover rule, or by making its selector more specific, or by moving it after the original class in the CSS.
Maybe you should try to set the !important
flag in the CSS.
.highlight {
background-color: #ff0000 !important;
}
I suspect the problem lies in how the original background color is applied and relates to cascade priority and specificity. The CSS selector for the original background color is probably more specific than the class and takes precedence. For example, a selector that specifies an element by id or by it's position in the DOM is more specific than a simple class designator. Making the class declaration !important
or reducing the specificity of the original CSS selector (if possible) should both work.
try
background-color:#f00 !important;
If you have two classes, and they both specify a background color, then which color is used depends on where the styles for the two class are defined.
精彩评论