效果图:
原代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 300px;
height: 300px;
background-color:orange;
border-radius:50%;
position:absolute;
}
button{
padding:5px 10px;
margin-top:100px;
}
</style>
</head>
<body>
<button>0</button>
<button>400</button>
<button>800</button>
<div id="box"></div>
<script>
var box=document.getElementById("box");
var btns=document.getElementsByTagName("button");
btns[0].onclick=function(){
constant_speed_X(box,0)
};
btns[1].onclick=function(){
constant_speed_X(box,400)
};
btns[2].onclick=function(){
constant_speed_X(box,800)
};
function constant_speed_X(ele,endX){
//1.要用定时器先清除定时器
clearInterval(ele.timer);
//2.通过判断获取步长,终点位置在当前位置的前面,步长为正,相反则为负
var step=endX>ele.offsetLeft?10:-10;
//3.启动定时器
ele.timer=setInterval(function(){
//4.位移元素
ele.style.left=ele.offsetLeft+step+"px";
//5.判断停止定时器,当终点位置与当前位置的距离的绝对值小于一个步长就停止定时器
if(Math.abs(endX-ele.offsetLeft)<=Math.abs(step)){
clearInterval(ele.timer);
//6.剩下小于一个步长的距离直接通过闪动动画拉到终点位置
ele.style.left=endX+"px";
}
},30)
}
</script>
</body>
</html>