<body>
<button>move-right</button>
<button>move-left</button>
<div id="box"></div>
</body>
<style>
body{
margin: 0;
}
#box{
position: absolute;
left: 10px;
background-color: red;
width: 100px;
height: 100px;
box-sizing: border-box;
}
</style>
<script>
window.onload = function(){
var box = document.getElementById('box');
var btn1 = document.getElementsByTagName('button')[0];
var btn2 = document.getElementsByTagName('button')[1];
btn1.onclick = function(){
move(box,500);
}
btn2.onclick = function(){
move(box,10);
}
var time = null;
var speed = null;
function move(elem,itarget){
clearInterval(time);
time = setInterval(function(){
speed = (itarget-elem.offsetLeft)/20;
if(speed>0){
speed = Math.ceil((itarget-elem.offsetLeft)/20);
}else{
speed = Math.floor((itarget-elem.offsetLeft)/20);
}
if(parseInt(elem.style.left)==itarget){
clearInterval(time);
}else{
elem.style.left = elem.offsetLeft + speed + "px";
}
}, 30)
}
}
</script>
网友评论