if(obj.offsetLeft
速度=(itarget-obj.offsetLeft)/10;
}else{
速度=-(obj.offsetLeft-itarget)/10;
speed>0?Math.ceil (speed):Math.floor(speed);//1px 未満の最終ディスプレイスメントが無視される問題を解決するための丸め処理
if(obj.offsetLeft==itarget){
clearInterval(timer);
ment.title=obj.offsetLeft;
},30 );
}
Key points:
①Achieve speed change by decreasing the speed value.
② Move to the end, when the pixel is less than 1px, several values less than 1px will not be added (or subtracted) to the object left, but will be ignored, so the final displacement is larger than the set horizontal displacement position itarget is a few pixels less. The solution is to round up: positive numbers are rounded up by ceil(), and negative numbers are rounded down by floor().
Extension: The principle of vertical displacement is the same as that of horizontal displacement.
Supplement 1:
Solve the problem that speed and itarget are not divisible, resulting in the object not accurately reaching the itarget position, but shaking around it:
var timer=null;
function moveto(object,itarget){
var obj=document.getElementById(object);
var speed=0;
If(obj.offsetLeft<=itarget) {
speed=7;
}else{
speed=-7;
}
// When the distance of itarget is less than speed, stop moving and set the object at the same time The left is moved directly to the position of itarget. itarget 'px' ;
}else{
.offsetLeft;
},30);
}
Supplement 2:
Bug in offset: For example, offsetWidth, which includes not only width, but also padding and border. When a padding or border is set for an object, and offsetWidth is assigned to the object, there will be a difference in movement.
Solution: Instead of using offset, create a function compatible with IE and FF to obtain the width attribute value of the element instead of offsetWidth. The function is as follows: getAttr()Copy code
The code is as follows:
return getComputedStyle(obj,false)[attrName]; //Compatible with FF }
}