jQuery animate()尽管stop()仍然成为香蕉 [英] jQuery animate() goes bananas despite stop()

查看:82
本文介绍了jQuery animate()尽管stop()仍然成为香蕉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在完成SVG计时器后,我得到了一个在悬停时会展开的框:

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

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

但是现在,如果您快速地徘徊很多次,它就会变成香蕉.为何将stop(true,true)放在每个animate()之前无法解决?

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;
}

推荐答案

此函数会将每个mouseenter的超时作业排队.定时函数解析后,它将停止元素上的任何动画,但不会清除其他定时函数.

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);
});

这篇关于jQuery animate()尽管stop()仍然成为香蕉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆