次のスクリプトは、ユーザーが画面の右端を上に移動し、ユーザーが画面の左端を上に移動したときに左にスクロールするという簡単な目的で書かれています。ただし、マウスを同じ場所に長時間放置すると、スクロールが終わりに達する前に停止します。後でマウスを動かすと再びスクロールを開始します。コードがマウスの位置を確認し、それに従ってスクロールする無限のタイムループを開始するので、なぜこれが起こっているのか理解できません。そのマウスが長すぎるために非アクティブである場合、マウスの位置が報告されなくなったかのようになります。何か案は?自動スクロールが突然停止する
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);
}