1

所以,我遇到了这种情况,但是如果用户“mouseleave(s)”超过 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);
                })
            ;
        });


});
4

3 回答 3

5

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;
        }
    })
;
于 2012-07-03T22:21:51.160 回答
3
$("#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);    
    };

});
于 2012-07-03T22:22:24.543 回答
2

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

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;});
于 2012-07-03T22:22:08.980 回答