效果:
代码:
<!DOCTYPE html>
<html>
<head>
<title>demo1</title>
<style type="text/css">
div {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0px;
}
</style>
</head>
<body>
<button id="btn">开始</button>
<div id="box"></div>
</body>
</html>
<script type="text/javascript">
var btn = document.getElementById("btn");
var box = document.getElementById("box");
var target = 400;
var timer = null;
btn.onclick = function(){
timer = setInterval(function(){
//盒子本身得位置 + 步长(不断变化)
var step = (target - box.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
box.style.left = box.offsetLeft + step + "px";
if (box.offsetLeft == target) {
clearInterval(timer);
alert("到位置了");
}
},30);
}
</script>