【问题标题】:Automatic Scrolling Suddenly Stops自动滚动突然停止
【发布时间】: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


    【解决方案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

    【讨论】:

      【解决方案2】:

      jQuery 的mousemove() 事件在e.pageX &gt; $(window).width()(或附近)时无法触发。对我来说看起来像一个 jQuery 错误。这可能会阻碍你的进步!

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        • 2011-09-04
        • 1970-01-01
        相关资源
        最近更新 更多