同上一篇添加了
- step判斷樊诺,判斷是正數(shù)就向右運(yùn)動(dòng),負(fù)數(shù)向左運(yùn)動(dòng)
- 運(yùn)動(dòng)到的目標(biāo)值使用形參的方式傳遞,這樣可以實(shí)現(xiàn)多個(gè)運(yùn)動(dòng)
<!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">運(yùn)動(dòng)到400</button>
<button id="btn2">運(yùn)動(dòng)到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>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者