js动画之链式运动
链式运动就是当一个运动完,又启动另外一个运动,这个怎么实现呢?这里我们是用用回调函数实现一套链式动画
显示给div左移100像素,然后然后透明度变100
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>链式运动</title> <style> .animation{ background-color: green; height: 200px; width: 200px; position: absolute; opacity: 0.3; left:0px; filter:alpha(opacity:30); } </style> </head> <body> <div id="test" class="animation" ></div> </body> <script type="text/javascript"> window.onload = function(){ var ele = document.getElementById("test"), timer = null; //alert(getStyle(ele,'opacity')) ele.onmouseover = function(){ startAnimation(ele,'left',100,function(){ startAnimation(ele,'opacity',100); }); } function startAnimation(node,attr,target,fn){ //1.清空定时器 clearInterval(timer); //2.重新生成一个定时器 timer = setInterval(function(){ var _currentAttrValue = null if(attr == 'opacity'){ _currentAttrValue = Math.round(parseFloat(getStyle(node,attr))*100); }else{ _currentAttrValue = parseInt(getStyle(node,attr)); } //3.当对应的属性到达了目标想要的属性,那么就清除定时器,并调用回调函数 if(_currentAttrValue == target){ clearInterval(timer); if(fn){ fn(); } }else{ _currentAttrValue ++ ; if(attr == 'opacity'){ node.style[attr] = _currentAttrValue/100; node.style.filter = 'alpha(opacity:'+_currentAttrValue+')'; }else{ console.log(_currentAttrValue); node.style[attr] = _currentAttrValue+'px'; } } },10) } function getStyle(ele,attr){ if(window.getComputedStyle){ return getComputedStyle(ele,null)[attr]; }else{ return ele.currentStyle[attr]; } } } </script> </html>
大家可以看看效果