jsアニメーションの多物体運動
2090 ワード
複数の物体これは1つのタイマーを使うことができなくて、すべての物体に1つのタイマーをあげます
ここでdivごとにタイマーをつけます~~bodyにmargin:0 pxを加えることに注意します;padding:0px;追加しないとobj.style.leftとobj.offsetLeftは等しくありません(ここでは相対的な位置決めを使用していますので)
<!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:0 pxを加えることに注意します;padding:0px;追加しないとobj.style.leftとobj.offsetLeftは等しくありません(ここでは相対的な位置決めを使用していますので)