苍狼之眼

js动画之同时运动

一个物体可以同时做多个运动,而不是完成一个运动再一个运动,而是让你感觉他们是同时发生的。

直接上代码

<!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;
    	ele.onmouseover = function(){
    		startAnimation(ele,{left:100,opacity:100},function(){
    		});
    		
    	}
    	
       function startAnimation(node,json,fn){
       	  //1.清空定时器
       	 clearInterval(timer);
       	 //2.重新生成一个定时器
       	 timer = setInterval(function(){
          //定义一个指标,所有的属性没有到达目标则不能清除定时器
          var success = false;
          for(attr in json){
            var target = json[attr];
       	 	  var _currentAttrValue = null;
       	 	  if(attr == 'opacity'){
       	 	  	_currentAttrValue = Math.round(parseFloat(getStyle(node,attr))*100);
       	 	  }else{
       	 	  	_currentAttrValue = parseInt(getStyle(node,attr));
       	 	  }
       	 	  
       	 	  if(_currentAttrValue == target){
       	 	  	break;
       	 	  }else{
              success = false; 
              if(_currentAttrValue > target){
                _currentAttrValue --;
              }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';
              }
            }
          }
          if(success){
            clearInterval(timer);
            if(fn){
              fn();
            }
          }
       	 },10)
       }

       function getStyle(ele,attr){

	       	if(window.getComputedStyle){
	       		return getComputedStyle(ele,null)[attr];
	       	}else{
	       		return ele.currentStyle[attr];
	       	}

       }
    	

    	
    }
 </script>
</html>

  自己去体会一下,当所有的属性到达目标的时候,才能清空定时器,不然有些属性没有到达属性的目标值就停止了。

大家可以可以去参考一下jquery的animate的方法,支持同时运动

posted on 2016-02-17 00:22  苍狼之眼  阅读(287)  评论(0编辑  收藏  举报

导航