苍狼之眼

js动画之多物体运动

多个物体这不能使用一个定时器了,要给每个物体一个定时器

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>多物体运动</title>
	<style>
    body{margin: 0px;padding: 0px;}
		.animation{
			background-color: green;
            margin: 10px 0px;
            padding: 0px;
			height: 100px;
			width: 100px;
			left: 0px;
			top: 0px;
            position: relative;
		}
	</style>
</head>
<body>
	<div  class="animation">A</div>
    <div  class="animation">B</div>
    <div  class="animation">C</div>
</body>
 <script type="text/javascript">
    window.onload = function(){
    	var ele = document.getElementsByTagName("div"),
            WINDOW_WIDTH = window.innerWidth - 100;
            for (var i = 0; i < ele.length; i++) {
                ele[i].timer = null;
                ele[i].onmouseover = function(){
                    startAnimation(this);
                }
            };
    	

    	function startAnimation(obj){
    		clearInterval(obj.timer);
    		obj.timer = setInterval(function(){
                var _left = obj.offsetLeft,
                    _speed = Math.ceil((WINDOW_WIDTH - _left)/100);

    			if (obj.offsetLeft >= WINDOW_WIDTH){
    				clearInterval(obj.timer);
    			}else{
                    obj.style.left = obj.offsetLeft+ _speed +'px';
                    console.log(obj.style.left);
                    console.log(obj.offsetLeft);
                }
    			
    		},1)
    	}

    	
    }
 </script>
</html>

  这里给每个div加上一个定时器~~ 还要注意的就是给body加上margin:0px;padding:0px;如果不加的话,那么obj.style.left和obj.offsetLeft是不会相等(因为我们这里使用的是相对定位)

posted on 2016-02-09 21:57  苍狼之眼  阅读(235)  评论(0编辑  收藏  举报

导航