js(多物体运动)
一、多物体运动
例如:创建三个div,每当鼠标移入其中一个变宽,移出恢复原来宽度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div {
width: 50px;
height: 50px;
background: red;
margin: 10px;
}
</style>
<script>
window.onload = function () {
var aDiv = document.getElementsByTagName('div');
for(var i=0;i<aDiv.length;i++){
aDiv[i].timer = null;//使每个div都有一个定时器,互不干扰
aDiv[i].onmouseover = function () {
startMove(this,400);
};
aDiv[i].onmouseout = function () {
startMove(this,50);
};
}
};
function startMove(obj,target) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var speed = (target-obj.offsetWidth)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(obj.offsetWidth == target){
clearInterval(obj.timer);
}else {
obj.style.width = obj.offsetWidth+speed+'px';
}
},30);
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>
浙公网安备 33010602011771号