如何激活鼠标离开,如果已经 x 时间



所以,我遇到了这种情况,但是如果用户"鼠标离开"超过x的时间,比如一秒钟,我只想"做某事"。我应该如何实现?

$("#someElement, #someOtherElement").mouseleave(function() {
   // Do something.
});

后来我补充说:

    $('.popover3-test').popover({
        placement:'bottom',
        template: $('.popover2'),
        trigger: 'manual',
        }).mouseenter(function(e) {
        $(this).popover('show');
        $(".popover3-test, .popover2").each(function() {
            var t = null;
            $(this)
                .mouseleave(function() {
                    t = setTimeout(function() {
                        $('.popover2').hide();
                    }, 1000); // Or however many milliseconds
                })
                .mouseenter(function() {
                    if(t !== null)
                        clearTimeout(t);
                })
            ;
        });

});

setTimeout应该可以做到这一点:

$("#someElement, #someOtherElement").each(function() {
    var t = null;
    $(this)
        .mouseleave(function() {
            t = setTimeout(function() {
                // Do something.
            }, 1000); // Or however many milliseconds
        })
        .mouseenter(function() {
            if(t !== null) {
                clearTimeout(t);
                t = null;
            }
        })
    ;
});

编辑:如果您希望它适用于其中任何一个,只需删除.each

var t = null;
$("#someElement, #someOtherElement")
    .mouseleave(function() {
        t = setTimeout(function() {
            // Do something.
        }, 1000); // Or however many milliseconds
    })
    .mouseenter(function() {
        if(t !== null) {
            clearTimeout(t);
            t = null;
        }
    })
;
$("#someElement, #someOtherElement").bind('mouseenter mouseleave', (function() {
    var timer;
    return function (e) {
       if(e.type === 'mouseleave') {
          timer = setTimeout(function () {
             //do something
          }, 1000);
       }  else {
          clearTimeout(timer);
       }
    };
}()));

编辑 - 可用于多个元素

$("#someElement, #someOtherElement").bind('mouseenter mouseleave', function (e) {
       var timer = $(this).data('timer');
       if(e.type === 'mouseleave') {
          timer = setTimeout(function () {
             //do something
          }, 1000);
       }  else {
          clearTimeout(timer);
       }
       $(this).data('timer', timer);    
    };
});

可能无法按原样工作,但会给你一些想法......

var elapsed = 0;
var timer = setInterval(function(){
  elapsed += 20;
  if( elapsed >= 1000 ) {
     doSomething();
     clearInterval(timer);
  }
}, 20 );
$('#some').mouseleave(timer);
$('#some').mouseenter(function(){clearInterval(timer);elapsed=0;});

最新更新