2013-12-17 57 views
0

我需要啓動,停止並重新啓動一個側面的動畫與一些搜索,我發現Jquery animate()需要一個插件做啓動 - 停止 - 重新啓動,但我不會使用這樣做的插件(而不是你的時間問「爲什麼不?」)。橫向動畫和setInterval()

於是,我就問我:??「你爲什麼不使用setInterval()這樣做橫向的動畫,並與clearInterval()停止

這是我的代碼,是正確的或者是瀏覽器的一個瘋狂的工作,我需要建立一個「efficent」(在瀏覽器方面的工作)腳本,但,我不是最好的這件事。可憐PLZ。

window.newsflash.interval = setInterval(function() { 
    if(liWidthTot + $('.fn_container ul').css("left") <= 0) 
     $('.fn_container ul').css('left', containerWidth); 
    $('.fn_container ul').css("left", "-=1px"); 
},10); 

//handler 
$("#xml").on({ 
    mouseenter: function(){ 
     clearInterval(window.newsflash.interval); 
    }, 
    mouseleave: function(){ 
     window.newsflash.interval = setInterval(function() { 
      if($('.fn_container ul').css("left") - liWidthTot <= 0) 
       $('.fn_container ul').css('left', containerWidth); 
      $('.fn_container ul').css("left", "-=1px"); 
     },10); 
    } 
}); 

它只是我的JS代碼的和平......我並不需要知道如何...但如果使用setInterval()是一個壞主意。

--- - 編輯----

現在:

var newsList = document.getElementById("newsList"); 
window.newsflash.interval = setInterval(function() { 
    if(liWidthTot + parseInt(newsList.style.left) <= 0) newsList.style.left = containerWidth +"px"; 
    ewsList.style.left = (parseInt(newsList.style.left) -1) + "px"; 
},10); 

//handler 
$("#xml").on({ 
    mouseenter: function(){ 
     clearInterval(window.newsflash.interval); 

    }, 
    mouseleave: function(){ 
     window.newsflash.interval = setInterval(function() { 
      if(liWidthTot + parseInt(newsList.style.left) <= 0) newsList.style.left = containerWidth +"px"; 
      newsList.style.left = (parseInt(newsList.style.left) -1) + "px"; 
     },10); 
    } 
}) 

THX隊友。

+1

查看此性能測試(比較js原生setInterval和jQuery動畫):http://jsperf.com/jquery-vs-javascript-animation – enyce12

+0

Thx ...是我想知道的。 – Frogmouth

回答

1

setInterval是做動畫的完全合法的方式。但使用jQuery的animate方法來啓動,停止和重新啓動動畫也很容易。在我看來,這兩種解決方案的表現大致相同,但是由您決定哪種語法更直接。

Demo using jQuery's $.animate()

Demo using setInterval()

在性能方面,你想要做的主要事情是確保你節省引用jQuery的對象,而不是重新獲得它們。你會發現,在我的例子我參考保存到ul這樣的:

var $ul = $('.fn_container ul'); 

...所以,它並沒有被一遍又一遍取出。

另外:您可能會考慮查看CSS3動畫以獲得更平滑的外觀。你甚至可以使用像jQuery Transit這樣的東西,以便你可以堅持使用jQuery動畫語法。

+0

Thx請參閱我的答案中的編輯?有一些建議? – Frogmouth