<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>运动</title>
<meta name="keywords" content="关键字列表" />
<style type="text/css">
#div1{width:100px;height:100px;background:pink;position:absolute;left:0; top:150px;}/*设置left值否则div将一直向右运动*/
</style>
<script type="text/javascript">
var timer = null;
function startMove(){
var oDiv1 = document.getElementById("div1");
clearInterval(timer); //先关掉定时器,(解决多次点击同时开启多个定时器的问题)
timer = setInterval(move,30);
function move(){
var ispeed = 1;
if(oDiv1.offsetLeft >= 400){ // 当运动到距离左大于等于400像素是关掉定时器,(或者判断当oDiv1.offsetLeft<400的时候再进行+10px的操作)
clearInterval(timer); //如果只是简单地使用if当运到停止后再次点击触发onclick事件div会再次向右移动10px; 原因是因为再次调用了定时器,在关闭定时器后,还会执行之后的代码
}else{
oDiv1.style.left = oDiv1.offsetLeft + ispeed +"px";
}
}
}
</script>
</head>
<body>
<input type = "button" value = "开始运动" onclick = "startMove()"/>
<div id = "div1"></div>
</body>
</html>
原文:http://www.cnblogs.com/clown3/p/5521457.html