jQuery .addClass 没有效果
各位编码人员,刚刚遇到了 .addClass 方法的奇怪行为(至少对我来说)。当鼠标悬停在项目 (div) 上时,我尝试使用 .addClass 方法和更改 div 背景颜色的 .highlight 类来突出显示该项目。 (我使用 jQuery 而不是 css :hover 方法是有原因的。)
代码的工作原理是,.highlight 类被添加到 div 但颜色没有改变。仅当 div 的默认 css 类中未定义背景颜色时,颜色才会更改。换句话说,如果 div 定义的类包含背景颜色:白色;添加了 .highlight 类,但颜色没有改变。
这是正常现象还是我错过了什么?现在,我正在使用 .css('background-color', ....) 来突出显示,但我很好奇为什么 .addClass 方法不起作用。
谢谢。
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 working.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您原来的 CSS 类将覆盖新的 CSS 类。
您可以通过将
!important
添加到悬停规则,或者使其选择器更加具体,或者将其移至 CSS 中的原始类之后来防止这种情况发生。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.也许您应该尝试在 CSS 中设置
!important
标志。Maybe you should try to set the
!important
flag in the CSS.我怀疑问题在于原始背景颜色的应用方式,并且与 级联优先级和特异性< /a>.原始背景颜色的 CSS 选择器可能比类更具体并且优先。例如,通过 id 或元素在 DOM 中的位置指定元素的选择器比简单的类指示符更具体。使类声明
!important
或减少原始 CSS 选择器的特殊性(如果可能)应该都可以。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
如果您有两个类,并且它们都指定了背景颜色,则使用哪种颜色取决于定义这两个类的样式的位置。
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.