【发布时间】:2012-02-27 17:49:12
【问题描述】:
我编写了以下脚本,目的很简单:当用户将鼠标悬停在屏幕右侧时向右滚动,当用户将鼠标悬停在屏幕左侧时向左滚动。它工作得很好,除了如果你把鼠标放在同一个地方太久,那么滚动将在到达终点之前停止。如果您随后移动鼠标,它将再次开始滚动。我不明白为什么会发生这种情况,因为代码会启动一个无限定时循环,该循环会检查鼠标位置并相应地滚动。如果鼠标太长时间不活动,就好像鼠标位置停止报告。有什么想法吗?
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);
}
【问题讨论】:
标签: javascript jquery scroll timing