鼠標(biāo)移出時(shí),使offsetLeft為0的另一種方法
var timer = null;
window.onload = function(){
? var oDiv = document.getElementById('div1');
? var oDiv2 = document.getElementById('div2');
? oDiv.onmouseover = function(){
? ? Move(0);
? }
? oDiv.onmouseout = function(){
? ? Move(-200);
? }
}
//鼠標(biāo)移入,模塊右移;鼠標(biāo)移出,模塊左移
function Move(iTarget){
? var oDiv = document.getElementById('div1');
? //onmouseover、onmouseout事件發(fā)生時(shí),首先清空全局定時(shí)器timer,以免定時(shí)器疊加
? clearInterval(timer);
? var speed = 0;
? //勻速運(yùn)動(dòng):初始右側(cè),目標(biāo)左側(cè),速度為負(fù);初始左側(cè),目標(biāo)右側(cè),速度為正
? // if (oDiv.offsetLeft > iTarget) {
? //? ? ?speed = -1;
? //? ?}else{
? //? ? ?speed = 1;
? //? ?}
? //定時(shí)器工作,移動(dòng)模塊
? timer = setInterval(function(){
? ? //速度由快到慢:隨著定時(shí)器工作,(目標(biāo)值-當(dāng)前值)越來越小
? ? if (oDiv.offsetLeft > iTarget) {
? ? ? speed = Math.floor((iTarget - oDiv.offsetLeft)/10);
? ? ? console.log(speed);
? ? }else{
? ? ? speed = Math.ceil((iTarget - oDiv.offsetLeft)/10);
? ? ? console.log(speed);
? ? }
? ??
? ? //到達(dá)目標(biāo),清除定時(shí)器;否則定時(shí)器繼續(xù)工作
? ? if (oDiv.offsetLeft == iTarget) {
? ? ? clearInterval(timer);
? ? }else{
? ? ? oDiv.style.left = oDiv.offsetLeft + speed + 'px';
? ? }
? },10)
}
2018-06-01
好的 ok