js 实现物体移动 老是抖动
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
.div2{ width:200px; height:300px; background:red; position: absolute; top:50px;left:10px;}
input{ margin:10px 0 0 80px;}
</style>
<script>
window.onload=function(){
var aDiv=document.getElementsByTagName('div');
var aInp=document.getElementsByTagName('input');
var timer=null;
aInp[0].onclick=function(){
doMove(aDiv[0],12,800)
} ;
function getStyle(obj,attr){
return obj.currentStyle? obj.currentStyle[attr] :getComputedStyle(obj)[attr];
}
aInp[1].onclick=function(){
doMove(aDiv[0],-12,10)
} ;
function getStyle(obj,attr){
return obj.currentStyle? obj.currentStyle[attr] :getComputedStyle(obj)[attr];
}
function doMove(obj,dir,target){
clearInterval(obj.timer)
timer=setInterval( function(){
var speed=parseInt(getStyle(obj,'left')) +dir;
if( speed>target && dir>0){ //往前跑
speed=target;
}
if( speed<target && dir<0){ //往后跑
speed=target;
}
obj.style.left=speed + 'px'
if(speed==target){
clearInterval(obj.timer)
}
},100)
}
}
</script>
</head>
<body>
<input type="button" value="往前">
<input type="button" value="往后">
<div class="div2">
</div>
</body>
</html>
你的timer刷新了但是clearTimer读的旧值,所以你的clearTimer从来都没有生效