网站搜索

javascript - 在按下鼠标时逐渐滚动,直到松开鼠标


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

答案#1

在这里,你可以使用 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);
});

CodePen 演示

我针对 $ ('html, body') 进行操作,以便它在 Firefox 和 Chrome 中都能工作。这有点棘手,因为 animate() 实际上会因为两个选择器而运行两次。为了解决这个问题,我使用了 jQuery.stop()。由于 Firefox 可以使用 $ ('html').scrollTop(),而 Chrome 使用 $ ('body').scrollTop(),我使用 Math.max() 计算增量。该函数在完成后会自执行,并在松开鼠标时使用 clearTimeout() 和 jQuery.stop()。