简体   繁体   中英

Jquery mouseleave event on two elements

I want to trigger an event when the mouse leaves two elements. I found the following jsfiddle which is exactly what I'm looking for:

http://jsfiddle.net/pFTfm/54/

It uses this code:

var count = 0;
$('#d1, #d2').mouseenter(function(){
    count++;
    $('#d3').show();
}).mouseleave(function(){
    count--;
    if (count == 0) { 
        $('#d3').hide();
        $('#d3').css('background-color', 'orange');
    }
});
​

However, the event still gets triggered, as you can see by the div changing its background color.

I want the event only to be triggered when the mouse really leaves both elements.

How about:

var count=0;
$('#d1, #d2').mouseenter(function(){
    count++;
    $('#d3').hide();
}).mouseleave(function(){
    count--;

    setTimeout(function(){
        if (count==0){
                $('#d3').show();
            }
    },50);
});
​

jsFiddle

The small timeout is to make sure the mouse actually left both elements, rather than left one and entered another.

You can't prevent the events from happening, but you can check the related target (the element you came from) and check if it's one or the other. If it is, just return from the event handler.

Something like:

var checkRelated = function(e) {
    var id = e.relatedTarget.id;
    return id == 'd1' || id == 'd2';
}

$('#d1, #d2').mouseenter(function(e){
    if (checkRelated(e)) return;
    $('#d3').show();
}).mouseleave(function(e){
    if (checkRelated(e)) return;
    // now we know we actually left both elements
    $('#d3').hide();
});

Demo: http://jsfiddle.net/pFTfm/57/

Another variation using .setTimeout()

var timer;

$('#d1, #d2').hover(function(){
    if( timer ) clearTimeout( timer );
    $('#d3').show();
},
function(){
    timer = setTimeout( function( ) {
        $('#d3').hide().css('background-color', 'orange');
    }, 100 );
});

Fiddle here

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