jQuery animate() goes bananas despite stop()

浪子不回头ぞ 提交于 2019-12-11 19:03:19

问题


I got this box that expands on hover after its SVG timer is done:

http://jsfiddle.net/frank_o/WwD5V/9/embedded/result/

But right now it goes bananas if you hover on and off many times quickly. How come placing stop(true,true) before each animate() won't fix it?

JS:

$('.wrapper').bind('mouseenter', function () {
    setTimeout(function () {
        $('.wrapper').stop(true,true).animate({
            width: '100%'
        }, 200);
    }, 2000);
}).mouseleave(function () {
    $('.wrapper').stop(true,true).animate({
        width: '120px'
    }, 200);
});

HTML:

<div class="wrapper">
    <div class="main"></div>
</div>

CSS:

.wrapper {
    height: 600px;
    width: 200px;
    overflow: hidden;
    border: 4px solid black;
    float: right;
}

回答1:


This function is queue a timeout job for each mouseenter. When the timed function resolves it will stop any animation on the element, but it will not clear other timed functions.

$('.wrapper').bind('mouseenter', function () {
    setTimeout(function () {
        var $this = $('.wrapper');

        $this.stop(true,true).animate({
            width: '100%'
        }, 200);

        $this.find('.main').stop(true,true).animate({
            left: '150%'
        }, 200);
    }, 2000);
});

So to fix, you need to check if the timeout is already set, and clear it first:

$('.wrapper').bind('mouseenter', function () {
    var timeoutHandle = $(this).data('timeout') || 0; 

    if (timeoutHandle > 0)
        clearTimeout(timeoutHandle);

    timeoutHandle = setTimeout(function () {
        var $this = $('.wrapper');

        $this.stop(true,true).animate({
            width: '100%'
        }, 200);

        $this.find('.main').stop(true,true).animate({
            left: '150%'
        }, 200);
    }, 2000);

    $(this).data('timeout', timeoutHandle);
});


来源:https://stackoverflow.com/questions/23922264/jquery-animate-goes-bananas-despite-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!