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