function animate(obj, target) { clearInterval(obj.timer); obj.timer = setInterval(function () { var leader = obj.offsetLeft; var step = 10;//之前只能是正数 只能往右走 /*if (leader < target) { step = step; } else { step = -step; }*/ step = leader < target ? step : -step; //if (leader != target) { //Math.abs(target - leader) 当前位置到目标的距离 //当前位置到目标的距离如果很大 这一步迈出之后 到不了目标 或者正好到 // 就可以迈出这一步 if (Math.abs(target - leader) >= Math.abs(step)) { leader = leader + step; obj.style.left = leader + "px"; } else { //就差一点儿了手动放到目标即可 obj.style.left = target + "px"; clearInterval(obj.timer); } }, 15); }