注意:每个物体需要单独使用一个定时器
样例1:多个div变宽
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {height: 50px;width: 100px;background: red;margin: 10px;}
</style>
<script>
window.onclick =function(){
var aDiv =document.getElementsByTagName("div");
for(var i = 0; i < aDiv.length; i++){
aDiv[i].timer = null;
aDiv[i].onmouseover = function(){
startMove(this,400);
}
aDiv[i].onmouseout = function(){
startMove(this,100);
}
}
}
function startMove (obj,iTarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
if(obj.offsetWidth == iTarget){
clearInterval(obj.timer);
}
else {
var speed = (iTarget - obj.offsetWidth) / 6;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
obj.style.width = obj.offsetWidth + speed + 'px';
}
},30);
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>
样例2:多个div淡入淡出:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div{height: 200px;width: 200px;background: red;margin: 20px;float: left;
filter: alpha(opacity:30);opacity: 0.3;}
</style>
<script>
window.onclick = function(){
var aDiv = document.getElementsByTagName("div");
for(var i = 0; i < aDiv.length; i++){
aDiv[i].timer = null;
aDiv[i].alpha = 30;
aDiv[i].onmouseover = function(){
startMove(this,100);
}
aDiv[i].onmouseout = function(){
startMove(this,30);
}
}
}
function startMove(obj,iTarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var speed = (iTarget - obj.alpha)/6;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if(obj.alpha == iTarget){
clearInterval(obj.timer);
}
else {
obj.alpha += speed;
obj.style.filter = 'alpha(opacity'+obj.alpha+')';
obj.style.opacity = obj.alpha / 100;
}
},30);
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
从两个例子可以看出:对于多物体运动来说,不能使用公用的参数,可以通过添加属性来完成。