2013-01-04 18 views
0

我有一個功能設置不斷循環的動畫像這樣:jQuery的 - 結束了「連續」動畫/功能

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

的片段按預期工作,但我在尋找最有效的方法來取消當一個外部div(例如#stopbutton,用於測試目的)循環。所以當用戶點擊div #stopbutton時,boxGlow()函數將停止,並且不透明度重置爲0.任何有關從何處開始的示例都將非常感謝。

+0

Yo我基本上使用遞歸回調。只需使用'setInterval'設置一個循環,並用'clearInterval'將其取消。 – Blender

+0

根據我的說法,一旦我clearInterval'我將無法重新啓動循環。這是真的?如果這樣可以避免或解決這個問題呢? – Alex

回答

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