首页 > js 实现物体移动 老是抖动

js 实现物体移动 老是抖动

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从来都没有生效

function doMove(obj,dir,target){
    // ....
    obj.timer=setInterval(function() { // timer => obj.timer
        // ....
    }, 100);
    // ....
}

不要用定时器吧,用animate({left:"0px"},1000),具体参数值可以自己去调试


做动画,你可以尝试CSS3的一些属性。

transaction
transform

比js使用定时器做性能会好很多,另外像位移这种变换,使用translate3d可以使用设备的硬件加速。比直接改left属性要好很多。

如果你坚持使用JS做动画,尽可能使用requestAnimationFrame这个方法会比直接使用set timeout性能要好得多

【热门文章】
【热门文章】