2012-02-27 84 views
0

我寫了下面的腳本,其目的是當用戶將鼠標懸停在屏幕的右側並向用戶移動到屏幕左側時向左滾動。它可以正常工作,但是如果您將鼠標放在同一個地方的時間太長,那麼滾動會在到達結尾之前停止。如果您隨後移動鼠標,它會再次開始滾動。我不明白爲什麼會發生這種情況,因爲代碼會啓動一個無限定時循環來檢查鼠標位置並相應滾動。就好像如果鼠標閒置時間過長,鼠標位置停止報告。有任何想法嗎?自動滾動突然停止

var mouseX = 0; 
var scrollX = 0; 
var timer; 
$(document).ready(function() { 
    // Record the mouse position if the mouse is moved 
    $(document).mousemove(function(e) { 
     mouseX = e.pageX; 
    }); 
    // Record the scroll position if the page is scrolled 
    $(document).scroll(function() { 
     scrollX = $(window).scrollLeft(); 
    }); 
    // Initiate the scrolling loop 
    scroll(); 
}); 

function scroll() { 
    // If the user is hovering over the right side of the window 
    if ((mouseX - scrollX) > 0.75*$(window).width()) { 
     scrollX += 1; 
     $(window).scrollLeft(scrollX); 
    } 
    // If the user is hovering over the left side of the window 
    if ((mouseX - scrollX) < (0.25*$(window).width())) { 
     scrollX -= 1; 
     $(window).scrollLeft(scrollX); 
    } 
    // Repeat in 5 ms 
    timer = window.setTimeout('scroll()', 5); 
} 

回答

1

我不知道你的代碼究竟出了什麼問題,但你爲什麼不使用jQuery的動畫? 這比編寫你自己的更可靠。

//inside $(document).ready(): 

var which = 0; 
$('body').mousemove(function(e) { 
    var w_width = $(window).innerWidth(); 
    var prc = (e.pageX - $(window).scrollLeft())/w_width; 

    var next_which = prc < 0.25 ? -1 : (prc > 0.75 ? 1 : 0); 

    if (next_which == which) 
     return; 

    which = next_which; 
    $('html,body').stop(true); 
    if (which != 0) 
     $('html,body').animate({scrollLeft: (which > 0 ? $(document).innerWidth()-w_width : 0)}, 2000); 

}).mouseleave(function() { 
    $('html,body').stop(true);  
    which = 0; 
}); 
​ ​ 

fiddle

0

jQuery的mousemove()事件無法何時啓e.pageX > $(window).width()(或左右)。看起來像一個jQuery的bug。這可能會阻礙你的進步!