逐渐在mousedown上滚动直到mouseup

Sco*_*ter 5 javascript jquery

当在position: fixed元素上按下鼠标按钮时,如何使视口逐渐向下滚动?

Dae*_*rik 5

在这里,您可以使用jQuery.animate()结合setTimeout()clearTimeout()来完成此操作:

$('.button').on('mousedown', function() {
    console.log('Start Animate');
    (function smoothSrcroll() {
        console.log(Math.max($('html').scrollTop(), $('body').scrollTop()));
        $('html, body').stop().animate({
            scrollTop: Math.max($('html').scrollTop(), $('body').scrollTop()) + 100
        }, 1000, 'linear', function() {
            window.timeout = setTimeout(smoothSrcroll(), 0);
        });
    })();
}).on('mouseup', function() {
    console.log('Stop Animate');
    $('html, body').stop();
    clearTimeout(window.timeout);
});
Run Code Online (Sandbox Code Playgroud)

代码笔演示

我的目标$('html, body')是它可以在 Firefox 和 Chrome 中运行。这有点棘手,因为animate()由于两个选择器,实际上运行了两次。为了解决这个问题,我使用了jQuery.stop()。由于 Firefox 可以使用 ,$('html').scrollTop()而 Chrome 使用$('body').scrollTop(),我使用Math.max()计算了增量。该函数在完成和使用clearTimeout()以及jQuery.stop()释放鼠标时自动执行。