简体   繁体   中英

CSS hover effect does not work after running jquery function

Here is my css:

.parentDiv {
}

.childDiv {
    height:40px;
    width:165px;
    color:#D6D6D6;
    text-align:left;
    cursor:pointer;
    font-size:.85em;
    font-weight:normal;
    border-top:1px solid #0F0F0F;
}

.childDiv:hover{
    background:#2B2B2B;
}

Here is my jquery:

<script type="text/javascript">

    $('.childDiv').click(function(){
        $(this)
            .css('background-color','#4F94CD')
            .siblings()
            .css('background-color','black');
    });

</script>

The div hover effect of the class childDiv work perfectly. However, once I run the above jquery function, the CSS hover effect no longer seems to work. It is essential that I am still able to use the hover effect after running this jquery function, I tried to look for a jquery substitute for the hover effect, but none worked perfectly. If anyone knows how to solve this, help would be greatly appreciated, thanks!

That sounds not weird...Try to set !important on the hover background, like this:

.childDiv:hover {
  background: #2b2b2b !important;
}

jQuery adds CSS directly to the element, and by CSS rules, the most specific CSS takes precedent. CSS applied directly is more specific than CSS applied by a style sheet.

To fix this, first apply the color using the same CSS ( background-color rather than background ), and then add !important to tell the browser that you want that style to override any others:

.childDiv:hover {
    background-color: #2b2b2b !important;
}

background: is technically valid, but is used as a shortcut when defining all background properties. And maybe you are, but here I do just to be sure we don't get any weird precedence rules.

Demo: http://jsfiddle.net/mYwh2/

This is because jquery apply styles by adding an in-line style attribute which overrides any css.

Your best solution would be to add classes rather than set css porperties - this will allow the css:hover to still function.

Try this:

.parentDiv{
}
.childDiv{
background-color: #000;
height:40px
width:165px;
color:#D6D6D6;
text-align:left;
cursor:pointer;
font-size:.85em;
font-weight:normal;
border-top:1px solid #0F0F0F;
}
.childDiv:hover{
background:#2B2B2B;
}
.selected{
background-color: #4F94CD;
}

with this jquery:

<script type="text/javascript">
$(function(){
    $('.childDiv').click(function(){
        $(this).toggleClass('selected');
    });
});

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