<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0px;
padding:0;
}
.active{
border:1px solid red;
width:100px;
height:50px;
}
.div1{
width:100px;
height:100px;
margin-top: 100px;
background-color: green;
position:absolute;
left:1000px;
top:20px;
}
.div2{
width:1px;
height:500px;
margin-top: 0px;
position:absolute;
left:500px;
top:0px;
background-color: black;
}
</style>
</head>
<body>
<input type="button" value="开始运动">
<div class="div1" >
</div>
<div class="div2"></div>
<script>
//运动的注意点
//定时器需要定义在运动函数外面以便于清除之前的定时器 var timer=null;
//在定时器开始之前要记得clearInterval()清除之前的
//根据物体的目的位置(destination)和物体当前的位置(offsetLeft)来判断向左还是向右移动
//控制向左还是向右运动就是offsetLeft加上或者减去一个值(speed)逐渐改变物体的left值
//加上则向右走 反之向左
//加速运动问题
//离目标地越远运动越快 越近则运动越慢-->根据两则的相对距离来动态改变速度(destinatin-offsetLeft)
//速度一开始过大,导致物体一下子到达目标点---->(destinatin-offsetLeft)/10;
//速度小数的问题,导致物体会停留在某一个位置;
//eg: destinetion:300px
//1.speed=0.9 offsetLeft=291-->left=291.9px-->291px取整;
//2.-->offsetLeft=291-->speed=0.9如此循环
//3.物体在291位置跳动
//---->向上或者向下取整 整数0.9时候向上取整为1 Math.ceil();
//-0.9时候向下取整为 -1 Math.floor()
var timer;
function startMove(target){
var div1=document.getElementsByTagName('div')[0];
var speed=0;
clearInterval(timer);
timer=setInterval(function(){
if(target==div1.offsetLeft){
clearInterval(timer);
}else{
speed=(target-div1.offsetLeft)/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
div1.style.left=div1.offsetLeft+speed+"px";
}
},100);
}
window.onload=function(){
var input=document.getElementsByTagName('input')[0];
input.onclick=function(){
startMove(500);
}
}
</script>
</body>
</html>