jQuery - 结束'连续'动画/功能

时间:2013-01-04 00:11:45

标签: jquery animation loops

我有一个功能设置来连续循环动画:

$(document).ready(function() {
    function boxGlow() {
        $("#not_bg").animate({opacity:0}, 1000);
        $("#not_bg").animate({opacity:1}, 1000, boxGlow);    
    }
});

该代码片段按预期工作,但我正在寻找一种最有效的方法来取消外部div时的循环(例如#stopbutton,用于测试目的)。因此,当用户点击div #stopbutton时,boxGlow()函数将停止,不透明度将重置为0.非常感谢任何有关开始的示例。

3 个答案:

答案 0 :(得分:1)

一种非常简单的方法是设置标志。

$(document).ready(function() {

    var stop = false;

    $('#stopbutton').on('click', function() {
          stop = true;
    });

    function boxGlow() {

        if ( stop ) return;

        $("#not_bg").animate({opacity:0}, 1000);
        $("#not_bg").animate({opacity:1}, 1000, boxGlow);    
    }
}

答案 1 :(得分:0)

我认为使用javascript计时事件做到这一点会更好:JavaScript Timing Events
像这样:

 $(function()
    {
       var intv = setInterval(function()
       {
          $("#not_bg").animate({opacity:0}, 1000);
          $("#not_bg").animate({opacity:1}, 1000);
       },2000);
       $('#stop').click(function()
       {
          window.clearInterval(intv);
       });
    }};

答案 2 :(得分:0)

当点击事件发生时,您可以向div添加一个类:

$(document).ready(function() {
    $('#stopbutton').click(function(){
        $('#not_bg').stop().addClass('done').css({opacity:0});
    });
    (function boxGlow() {
        if(!this || !$(this).is('.done')){
            $("#not_bg").animate({opacity:0}, 1000);
            $("#not_bg").animate({opacity:1}, 1000, boxGlow);
        }
    })();
});

以下是演示:http://jsfiddle.net/N42rn/