<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JS运动之多个物体同时运动</title>
<style>
div{
width: 100px;
height:50px;
background-color: pink;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
<script type="text/javascript">
//多物体运动框架,参数1表示某一物体,参数2表示运动的目标状态
//var timer=null;
function startMove(obj,iTarget){
clearInterval(obj.timer); //在运动开始之前关闭定时器
obj.timer=setInterval(function(){
var speed=(iTarget-obj.offsetWidth)/6; //确定运动的速度大小
speed=speed>0?Math.ceil(speed):Math.floor(speed);
//Math.ceil(speed)将速度向上取整;Math.floor(speed)向下取整,Math.round(speed)标准四舍五入取整
if(obj.offsetWidth==iTarget){
clearInterval(obj.timer);
}
else{
obj.style.width=obj.offsetWidth+speed+'px';
}
},30);
};
aDiv=document.getElementsByTagName('div');
for(var i=0;i<aDiv.length;i++){
aDiv.timer=null; //给每个div都设置一个自己的计时器,这样运动时就不会相互打扰;这样的写法叫做自定义属性
//当多个物体都需要运动时,每个物体设置自己的定时器是比较好的
aDiv[i].οnmοuseοver=function(){
startMove(this,400);
};
aDiv[i].οnmοuseοut=function(){
startMove(this,100);
};
}
</script>
</html>
JS运动之多个物体同时运动,如何不相互干扰
最新推荐文章于 2022-11-17 20:29:30 发布