CSS悬停选择器的背景颜色不工作后的背景色与jquery的动态更改 [英] CSS hover selector for background-color not working after dynamic change of background-color with jquery

查看:111
本文介绍了CSS悬停选择器的背景颜色不工作后的背景色与jquery的动态更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我在说什么: http://jsfiddle.net/KVmCt/1/

解决方案

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



外部样式表被CSS在文档的头部覆盖;这又是由CSS在元素的 style 属性中超过的。基本上浏览器遇到的最后一个样式会覆盖任何以前指定的规则,除非使用!important 的关键字。



因为JavaScript,因此jQuery将其CSS /样式信息放入元素的内联 style 属性中。 always 重写颜色:red

c $ c> div ,忽略 div:hover 样式。



你可以使用:

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

JS Fiddle demo



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

  div {
background-color:红;
}

div:hover {
background-color:blue!important;或者,您可以使用jQuery的 hover()


$ b
方法:

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

JS Fiddle演示


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)?

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

解决方案

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

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).

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.

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 demo.

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;
}

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 demo.

这篇关于CSS悬停选择器的背景颜色不工作后的背景色与jquery的动态更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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