简体   繁体   中英

CSS hover and jquery

Hover effect of CSS is not executing anymore after jquery-action:

I do have the following CSS:

#slider-information-content{
  display: inline;
  visibility: hidden;
 }
#slider-information:hover  #slider-information-content {
  display: inline;
  visibility: visible;
}

and the following jquery code:

 $("#slider-information-content-close").click(function(e) {
     $("#slider-information-content").css("visibility", "hidden");
     e.preventDefault();
     return false;
 });

The hover effect is working fine. Also I can hide the div with jquery. But when I hide the div with jquery the hover effect is not working anymore and the div is not coming up. How can I change it? And also WHY?

JS Fiddle

Setting CSS on an element in JavaScript (or jQuery) applies the value to the element's style="..." attribute.

This has higher precedence than any rule in a stylesheet. In this case, you have 0210 as the precedence for your visibility: visible , but the .css("visibility","hidden") has a precedence of 1000 and therefore wins.

You can circumvent this by using:

#slider-information:hover #slider-information-content {
    visibility: visible !important;
}

However, the use of !important almost always means you're doing something wrong.

The problem with your code is, the visibility property set through jQuery is getting precedence as an inline style is set.

You can use jQuery .hover() for this,

$("#slider-information").hover(function (e) {

    $("#slider-information-content").css("visibility", "visible");

}, function (e) {

    $("#slider-information-content").css("visibility", "hidden");

});

Demo

You're mixing jQuery and CSS, which can be tricky. If you switch to using jQuery for both the hover and click behavior is will simplify the code and fix the issue.

http://jsfiddle.net/mcH7L/2/

CSS

#slider-information-content {
    display: inline;
    visibility: hidden;
}
#slider-information:hover #slider-information-content {
    display: inline;
    visibility: visible;
}

HTML

<div id="slider-information">Hover this
    <div id="slider-information-content">
        <div id="slider-information-content-close">Close</div>
        Hidden content here</div>
</div>

jQuery

$("#slider-information").hover(function (e) {
    $("#slider-information-content").show();
}, function (e) {
    $("#slider-information-content").hide();
});

$("#slider-information-content-close").click(function (e) {
     $("#slider-information-content").hide()
     e.preventDefault();
     return false;
});

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