我需要使用Javascript启动,停止并重新启动横向动画,有些搜索我发现Jquery animate()
需要一个插件来执行start-stop-restart,但我不会使用插件这样做(不要花时间问“为什么不呢?”)。
所以,我问我:“你为什么不用setInterval()
来做这个横向动画并用clearInterval()
来阻止它?
这是我的代码,是正确的还是浏览器的疯狂工作?我需要构建一个“高效”(就浏览器工作而言)脚本,但是,我并不是最好的。请怜悯。
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 mates。
答案 0 :(得分:1)
setInterval
是完全合法的动画制作方式。但是使用jQuery的animate
方法来启动,停止和重新启动动画也很容易。在我看来,两种解决方案的表现大致相同,但由您决定哪种语法更直接。
Demo using jQuery's $.animate()
就性能而言,您要做的主要是确保保存对jQuery对象的引用,而不是重新获取它们。您会注意到,在我的示例中,我将对ul
的引用保存为:
var $ul = $('.fn_container ul');
...这样就不必一遍又一遍地取出它。
另外:您可以考虑查看CSS3动画以获得更流畅的外观。您甚至可以使用jQuery Transit之类的东西,这样就可以坚持使用jQuery动画语法。