简体   繁体   中英

JQuery and strange behavior on hover function

I'm using a hover effect for all DIVs with class="box" on a page:

Javascript :

    JQ(".box").hover(function() {
        JQ(this).nextAll(".tooltip:first").css('visibility','visible');
    });

    JQ(".box").mouseleave(function(event) {
        JQ(this).nextAll(".tooltip:first").css('visibility','hidden');
    });

It works fine in Firefox and Chrome but in IE9 and Opera the .tooltip div disappears and re-appears continuously when the mouse moves within the boundaries of the .box DIV. any ideas why the hover function keeps being called for every pixel of the DIV?

You can see a working version here

When you only pass one function to .hover() that function is called when the mouse both enters and leaves. So, you're making it visible on both entering and leaving which is conflicting with your mouseleave handler.

You could just do this:

JQ(".box").hover(function() {
    JQ(this).nextAll(".tooltip:first").css('visibility','visible');
}, function() {
    JQ(this).nextAll(".tooltip:first").css('visibility','hidden');
});

Or, a little more DRY (less repeated code):

JQ.fn.nextTip = function(vis) {
    return this.nextAll(".tooltip:first").css('visibility', vis);
}

JQ(".box").hover(function() {
    JQ(this).nextTip('visible');
}, function() {
    JQ(this).nextTip('hidden');
});

Working demo: http://jsfiddle.net/jfriend00/DkgVg/

You should try replacing the hover part with:

JQ(".box").mouseenter(function() {
    JQ(this).nextAll(".tooltip:first").css('visibility','visible');
});

Or keep hover and do:

JQ(".box").hover(function() {
    JQ(this).nextAll(".tooltip:first").css('visibility','visible');
}, function(){
    JQ(this).nextAll(".tooltip:first").css('visibility','hidden');
});

Just stop execution of event functions for this jQuery object

JQ(".box").hover(function() {
    JQ(this).nextAll(".tooltip:first").stop(true,true).css('visibility','visible');
}, function(){
    JQ(this).nextAll(".tooltip:first").stop(true,true).css('visibility','hidden');
});

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