简体   繁体   中英

Text not changing color with jquery addClass()

http://jsfiddle.net/GHJX5/

I have a div with blue text and I want it to change on hover to yellow. For some reason, if I remove the CSS part that sets it blue it will change to yellow on hover, but if it's set to blue it will not.

JS

$('#registerbutton').hover(
    function() {
        $('#registerbutton').addClass('asd');
    }, function() {
        $('#registerbutton').removeClass('asd');
    }
);

HTML

<div id="registerbutton">click</div>

CSS

#registerbutton{
    color:blue;
}
.asd{
    color:yellow;
}

An ID is more specific than a class, therefore the class gets overruled. Try this instead:

#registerbutton.asd {
    color:yellow;
}

jsFiddle example

To learn more about CSS specificity, see https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

为什么你不使用简单的CSS属性悬停像这样

#registerbutton:hover{color:yellow;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM