同上一篇添加了
- step判断,判断是正数就向右运动,负数向左运动
- 运动到的目标值使用形参的方式传递,这样可以实现多个运动
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
</style>
<body>
<button id="btn1">运动到400</button>
<button id="btn2">运动到600</button>
<div id="box"></div>
<script type="text/javascript">
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var box = document.getElementById('box');
var timer = null;
btn1.onclick = function () {
animate(box, 400);
}
btn2.onclick = function () {
animate(box, 600);
}
function animate(tag, target) {
clearInterval(tag.timer);
tag.timer = setInterval(function () {
var current = tag.offsetLeft;
var step = (target - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
current = current + step;
tag.style.left = current + 'px';
if(current == target) {
clearInterval(tag.timer);
}
},30)
}
</script>
</body>
</html>