运动终止条件:
匀速运动:距离足够近,常常用到Math.abs();
缓冲运动,两点重合,常常用到 Math.ceil(); Math.floor();
匀速运动:
<html lang="en"> <head> <meta charset="UTF-8"> <title>匀速运动</title> <style> div{width:100px;height:100px;background-color:green;position:absolute;left:0px;top:0;} input{margin-top:120px;} span{height:300px;width:1px;background:black;display:block;position:absolute;left:300px;top:0;} </style> </head> <body> <div id="div1"></div> <input type="button" value="开始运动" onclick="startMove(300)"> <span></span> </body> </html> <script> var time = null; function startMove(iTarget) { var oDiv = document.getElementById("div1"); clearInterval(time); time = setInterval(function () { var spend = 0; if(oDiv.offsetLeft<iTarget){ spend = 7; }else{ spend = -7; } if(Math.abs(oDiv.offsetLeft-iTarget)<7){//是否到达终点 clearInterval(time);//到达终点以后 oDiv.style.left = iTarget+‘px‘; }else{ oDiv.style.left = oDiv.offsetLeft+spend+"px";//到达之前 } },30); } </script>
缓冲运动:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>div移动</title> <style> div{width:100px;height:100px;background-color:green;position:absolute;left:500px;top:0;} input{margin-top:120px;} textarea{width:100%;margin-top:150px;} span{height:300px;width:1px;background:black;display:block;position:absolute;left:300px;top:0;} </style> </head> <body> <div id="div1"></div> <input type="button" value="开始运动" onclick="startMove(300)"> <textarea name="" id="txt1" cols="30" rows="10"></textarea> <span></span> </body> </html> <script type="text/javascript"> var time = null; function startMove(iTarget) { var oDiv = document.getElementById("div1"); var oTxt = document.getElementById("txt1"); clearInterval(time); time = setInterval(function () { var spend = (iTarget-oDiv.offsetLeft)/8;//这里必须取整 // if(spend>0){//当值为正数的时候,向上取整 // spend = Math.ceil(spend); // }else{//当值为正数的时候,向上取整 // spend = Math.floor(spend); // } //可以简写成:问号前面是条件,后面是结果; spend = spend>0?Math.ceil(spend):Math.floor(spend); if(oDiv.offsetLeft == iTarget){//是否到达终点 clearInterval(time);//到达终点以后 }else{ oDiv.style.left = oDiv.offsetLeft+spend+"px";//到达之前 } oTxt.value +=spend+"\n"; document.title = oDiv.offsetLeft+spend; },30); } // 缓冲运动的问题 //小数问题,解决方案 //Math.ceil()当值为正数的时候,向上取整 // Math.floor()当值为负数的时候,向下取整 </script>
时间: 2024-10-13 15:21:50