2

我有一个递归动画来使屏幕上的文本改变颜色。当 div 失去可见性时,我想要一些机制来停止这个动画。在我的实际站点中,这是在一个对话框中。我想在对话框关闭时停止所有动画。我尝试使用$.stop(),但我认为这不会在递归调用期间中断调用堆栈。

这是我正在做的事情的要点:

javascript:

function rainbow() {
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $('#rainbow ul li').animate({
        color: hue
    }, 500, rainbow);
}
$(function() {
    rainbow();

    $("#stop").click(function() {

        $('#rainbow ul li').stop()

    });
});​

html

<div id="rainbow">
    <ul>
        <li>Apple</li>
        <li>Microsoft</li>
        <li>SUN</li>
    </ul>
</div>
<button id="stop" type="reset">Stop</button>

​</p>

http://jsfiddle.net/cRar7/12/

单击停止按钮不执行任何操作,动画继续。

4

3 回答 3

5

看看.stop的第一个参数

.stop( [clearQueue] [, jumpToEnd] )

clearQueue一个布尔值,指示是否也删除排队的动画。默认为假。

所以:

$('#rainbow ul li').stop(true);

应该管用。

http://jsfiddle.net/cRar7/14/

于 2012-04-26T15:00:16.660 回答
1

好吧,你可以使用一个标志来做到这一点:

var shouldStop = false;
function rainbow() {
    if(shouldStop) return;
    // rest of animation code here
}

$("#stop").click(function() {
    shouldStop = true;
    $('#rainbow ul li').stop();
});

这是演示:http: //jsfiddle.net/cRar7/13/

于 2012-04-26T14:59:04.453 回答
0

如果您设置一个间隔而不是设置动画自递归,那没问题。将您的脚本更改为:

function rainbow() {
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $('#rainbow ul li').animate({
        color: hue
    }, 500);
}
$(function() {
    var ani=setInterval(rainbow,500);

    $("#stop").click(function() {

        clearInterval(ani);

    });
});
于 2012-04-26T15:03:34.637 回答