0

正常的鼠标离开功能可以正常工作,但是如果我们离开鼠标的速度非常慢,那么鼠标退出功能就无法正常工作..

var timeoutId;
$('.box').mouseover(function(){
        var $this=$(this);
        if (!timeoutId) {
            timeoutId = window.setTimeout(function() {
            timeoutId = null;
                $this.animate({
                    marginTop:'-224px',
                    height:'300px'
                    })
    $this.find('.rotate-arrow').addClass('rotate');
    $this.find('.header-content-span').css('display','none');
                                                   },1000); }
            });
$('.box').mouseleave(function(){
        var $this=$(this);
         if (timeoutId) {
            window.clearTimeout(timeoutId);
            timeoutId = null;
            $this.animate({
                marginTop:'0px',
                height:'77px'
                })
    $this.find('.rotate-arrow').removeClass('rotate');
    $this.find('.header-content-span').css('display','block');

        }
4

1 回答 1

2

代码设置的方式,mouseleave如果您碰巧在.box容器上停留超过一秒钟,动画将不会出现。

这是因为timeoutId一旦setTimeout触发就会被清除,并且mouseleave回调包含仅在定义了动画时才执行动画的逻辑timeoutId

要解决此问题,只需将动画从 if 语句中拉出。这是一个简化的示例:

var timeoutId;
$('.box').mouseenter(function () {
    var $this = $(this);
    if (!timeoutId) {
        timeoutId = window.setTimeout(function () {
            timeoutId = null;
            $this.stop().animate({
                height: '100px'
            });
        }, 1000);
    }
});
$('.box').mouseleave(function () {
    var $this = $(this);
    if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
    }
    $this.stop().animate({
        height: '50px'
    });
});

注意:我使用mouseenter它是因为它与mouseleave. 根据您的具体情况,这两个处理程序往往是比使用更好的选择,mouseover并且mouseout由于它们为绑定对象的后代处理事件冒泡的方式。

jsfiddle

于 2013-02-21T08:25:35.183 回答