<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box{
position: relative;
top: 0;
left: 100px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div> <button>向左</button> <button>向右</button>
<script src="./tools.js"></script>
<script>
var oBox = document.getElementById('box');
var oLeft = document.getElementsByTagName('button')[0];
var oRight = document.getElementsByTagName('button')[1];
var timer = null;
oRight.onclick = function(){
clearInterval(timer);
var l = parseInt(getCss(oBox,'left'));//'100'
timer = setInterval(function(){
l+=5;
if(l >= 500){
clearInterval(timer);
}
oBox.style.left = l + 'px';
},20);
}
oLeft.onclick = function(){
//點擊左按鈕先清除定時器,停在當前位置
clearInterval(timer);
var l = parseInt(getCss(oBox,'left'));
timer = setInterval(function(){
l-=5;
if(l<=0){
clearInterval(timer);
}
oBox.style.left = l + 'px';
},20);
}
</script>
</body>
</html>
實現效果如下