| |
<!DOCTYPE html> |
| |
<html lang="en"> |
| |
<head> |
| |
<meta charset="UTF-8"> |
| |
<title>定时器练习</title> |
| |
|
| |
<style type="text/css"> |
| |
#div1{ |
| |
100px; |
| |
height: 100px; |
| |
background: #666; |
| |
margin-top: 20px; |
| |
position: absolute; |
| |
left: 0; |
| |
} |
| |
|
| |
|
| |
</style> |
| |
<script type="text/javascript"> |
| |
window.onload=function(){ |
| |
var oBtn=document.getElementById('btn1'); |
| |
var oBtn1=document.getElementById('btn2'); |
| |
var oDiv=document.getElementById('div1'); |
| |
var timer=null; |
| |
|
| |
oBtn.onclick=function(){ |
| |
move(oDiv,19,500); |
| |
} |
| |
|
| |
oBtn1.onclick=function(){ |
| |
move(oDiv,-10,0); |
| |
} |
| |
|
| |
function move(obj,speed,iTarget){ |
| |
clearInterval(timer) |
| |
timer=setInterval(function(){ |
| |
var long=oDiv.offsetLeft+speed; |
| |
if(long>=iTarget&&speed>0){ |
| |
long=iTarget |
| |
} |
| |
if(long<=iTarget&&speed<0){ |
| |
long=iTarget |
| |
} |
| |
oDiv.style.left=long+'px'; |
| |
|
| |
if(parseInt(oDiv.style.left)<=0){ |
| |
oDiv.style.left=0 |
| |
} |
| |
},30) |
| |
} |
| |
} |
| |
</script> |
| |
</head> |
| |
<body> |
| |
<button id="btn2">向左</button> |
| |
<button id="btn1">向右</button> |
| |
|
| |
<div id="div1"> |
| |
|
| |
</div> |
| |
</body> |
| |
</html> |
在线测试地址:http://codepen.io/itguy/pen/vGMpdg