想使用setTimeout做一个小动画,但是感觉自己写的代码太繁琐。想知道该如何简化这段代码。是否可以使用构造函数?
function jaTree(){
setTimeout("$('.tree-1 .line-z').css({'height':'100px'});",1000);
setTimeout("$('.tree-1 .tree-point').css({'opacity':'1'});",2000);
setTimeout("$('.tree-right-text-1').css({'opacity':'1','margin-left':'0px'});",2500);
setTimeout("$('.tree-2 .line-z').css({'height':'100px'});",3500);
setTimeout("$('.tree-2 .tree-point').css({'opacity':'1'});",4500);
setTimeout("$('.tree-right-text-2').css({'opacity':'1','margin-right':'0px'});",5000);
setTimeout("$('.tree-3 .line-z').css({'height':'100px'});",6000);
setTimeout("$('.tree-3 .tree-point').css({'opacity':'1'});",7000);
setTimeout("$('.tree-right-text-3').css({'opacity':'1','margin-left':'0px'});",7500);
setTimeout("$('.tree-4 .line-z').css({'height':'100px'});",8500);
setTimeout("$('.tree-4 .tree-point').css({'opacity':'1'});",9500);
setTimeout("$('.tree-right-text-4').css({'opacity':'1','margin-right':'0px'});",10000);
setTimeout("$('.tree-5 .line-z').css({'height':'100px'});",11000);
setTimeout("$('.tree-5 .tree-point').css({'opacity':'1'});",12000);
setTimeout("$('.tree-right-text-5').css({'opacity':'1','margin-left':'0px'});",12500);
setTimeout("$('.tree-6 .line-z').css({'height':'100px'});",13500);
setTimeout("$('.tree-6 .tree-point').css({'opacity':'1'});",14500);
setTimeout("$('.tree-right-text-6').css({'opacity':'1','margin-right':'0px'});",15000);
setTimeout("$('.tree-7 .line-z').css({'height':'100px'});",16000);
setTimeout("$('.tree-7 .tree-point').css({'opacity':'1'});",17000);
setTimeout("$('.tree-right-text-7').css({'opacity':'1','margin-left':'0px'});",17500);
setTimeout("$('.tree-8 .line-z').css({'height':'100px'});",18500);
setTimeout("$('.tree-foot').css({'opacity':'1'});",19500);
}
既然使用了jQuery,则使用animate()和queue()这两个API就OK了。
样式的东西就写在css中,js应用/移除样式即可。
如果不是为了兼容低版本浏览器,还是直接使用CSS3动画吧。性能好,动画流畅
建议使用css 实现动画,使用translate 改变位置会好一些。
从性能说CSS3动画是最佳选择,原生settimeout也是最佳选择(当然,别拿字符串当参数,要拿函数当参数)。
从写法简洁性讲,如果用CSS3,已经很简洁了。如果不支持CSS3,用jQuery的animate()和queue()也可以,当然性能差一点。
总之优选是css3,不行的话追求写法精炼就是jQuery,追求性能就是settimeout
楼主完全可以使用CSS3来实现动画。
setTimeout
不要这么用。字符串可以解析成函数,这从语法上来说是没有问题的。但是这样十分影响解释器运行的效率,一般在js编程中都是不推荐(严格的来说甚至是禁止)这么做的。
这样的动画有很多种实现方式,比如可以直接用css的动画去做,js里面只需要控制开闭就行了
另外,如果一定要用js来完成,你可以看看jquery中animate
的实现,我觉得这个api还是比较简洁美观的。
如果一定要像你这样一个阶段一个阶段的setTimeout
的话,我觉得用promise
封装一层,然后用then
串联起来会更好点,这样至少在语言逻辑上会简洁很多。