-->

jQuery Hover flickers if trigger div and targeted

2019-08-19 06:44发布

问题:

I have set up a very simple jQuery hover function, but the thing is when you hover over the trigger div, it works but if you move your mouse over the targeted div whilst still on the trigger div (the overlap) it flickers!? Any ideas?

I have this jQuery code:

            $("#tag").hover(
              function () {
                $("#homeHover").show();
              }, 
              function () {
                $("#homeHover").hide();
              }
            );

With this HTML structure:

<div id="homeHover"></div>
<div id="tag">

</div>

And this CSS:

#homeHover {
width: 150px;
height: 150px;
position: absolute;
background: url("../img/arrow.png") no-repeat scroll 0 0 transparent;
top: 145px;
left: 0px;
display: none;
}
#tag {
float: left;
}

回答1:

You can trigger a mouseenter and mouseleave event for the trigger div when you move over the targeted div. This will stop the flickering.

$("#homeHover").on({
    mouseenter: function(){
        // Trigger #tag hover to stop flickering
        $('#tag').mouseenter();
    }

    mouseleave: function(){
        // Trigger #tag mouseleave
        $('#tag').mouseleave();
    }
});


回答2:

$(document).mouseover(function(e) {
    if (e.target == $("#homeHover").get(0) || e.target == $("#tag").get(0)) {
        $("#homeHover").show();
    }
    else {
        $("#homeHover").hide();
    }

});