<body>
<button>
运动200
</button>
<button>运动400</button>
<div style=" 100px;height: 100px;background-color: pink;position: absolute;"></div>
</body>
var btn = document.getElementsByTagName('button')
var div = document.getElementsByTagName('div')[0]
// btn.onclick = function(){
// setInterval(function(){
// // 盒子的位置 = 盒子本身的位置 + (目标的位置 - 盒子的位置)/10
// div.style.left = div.offsetLeft+(400 - div.offsetLeft)/10 + 'px'
// },30)
// }
btn[0].onclick = function(){
animate(div,200)
}
btn[1].onclick = function(){
animate(div,400)
}
function animate(ele,target){
clearInterval(ele.timer);
ele.timer = setInterval(function(){
var step = (target - ele.offsetLeft)/10
step = step > 0?Math.ceil(step):Math.floor(step)
ele.style.left = ele.offsetLeft + step +'px'
if(Math.abs(target - ele.offsetLeft) <= Math.abs(step)){
ele.style.left = target + 'px'
clearInterval(ele.timer)
}
},30)
}