使用jquery动态更改背景颜色后,背景颜色的CSS悬停选择器不起作用

2022-01-22 00:00:00 hover jquery css

我使用 jquery .css() 方法动态更改 div 的背景颜色.我还想在改变背景颜色的同一个 div 上有一个 CSS hover 选择器.似乎在使用jquery更改颜色之前,CSS hover 选择器可以工作,但是在使用jquery方法更改div之后,CSS hover 选择器不再起作用.有没有办法解决这个问题(不使用 jquery hover 方法)?

I dynamically change the background color of a div with the jquery .css() method. I also want to have a CSS hover selector on that same div that changes the background color. It seems that before the color is changed with jquery, the CSS hover selector works, but after the div is changed with the jquery method, the CSS hover selector no longer works. Is there a way to work around this (without using the jquery hover method)?

这是我所说的一个例子:http://jsfiddle.net/KVmCt/1/

This is an example of what I'm talking about: http://jsfiddle.net/KVmCt/1/

推荐答案

你遇到的问题是CSS信息位置的重要性:

The problem you're experiencing is the importance of the location of the CSS information:

外部样式表被文档头部的 CSS 覆盖;这反过来又被元素的 style 属性中的 CSS 否决.基本上,浏览器遇到的最后一个样式会覆盖任何先前指定的,否则会发生冲突的规则(除非使用了 !important 的关键字).

An external stylesheet is over-ruled by CSS in the head of the document; which is, in turn, over-ruled by CSS in the style attribute of the element. Basically the last style encountered by the browser overrides any previously specified, and otherwise-conflicting, rules (unless the keyword of !important is used).

由于 JavaScript,因此 jQuery,将其 CSS/样式信息放入元素的内联 style 属性中,此 总是 覆盖其他地方指定的冲突样式.

As JavaScript, and therefore jQuery, places its CSS/styling information into the in-line style attribute of the element this always overrides conflicting styles specified elsewhere.

div 更重视 color: red,忽略 div:hover 样式.

The places more importance on the color: red for the div, disregarding the div:hover styles.

要解决它,您可以使用:

To work around it, you can use:

div:hover {
    background-color: blue!important;
}

JS Fiddle 演示.

不过,更好的解决方案是避免使用 jQuery 分配 background-color/其他样式,而只需使用 CSS:

A better solution, though, is to avoid assigning the background-color/other styles with jQuery, and simply use CSS:

div {
    background-color: red;
}

div:hover {
    background-color: blue!important;
}

或者,您可以使用 jQuery 的 hover() 方法:

Alternatively, you could use jQuery's hover() method:

$('div').css('background-color','red').hover(
    function(){
        $(this).css('background-color','blue');
    },
    function(){
        $(this).css('background-color','red');
    });

JS Fiddle 演示.

相关文章