简体   繁体   English

jQuery mouseleave事件在两个元素上

[英]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: 我发现以下jsfiddle正是我在寻找的东西:

http://jsfiddle.net/pFTfm/54/ 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. 但是,该事件仍会触发,如您通过div更改其背景颜色可以看到的那样。

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 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/ 演示: http//jsfiddle.net/pFTfm/57/

Another variation using .setTimeout() 使用.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 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM