如何在鼠标按住一个 position: fixed
元素时逐渐滚动视窗?
如何在鼠标按住一个 position: fixed
元素时逐渐滚动视窗?
你可以通过使用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);
});
我选择了$('html, body')
,以便在Firefox和Chrome中都能正常工作。这有点棘手,因为由于两个选择器的存在,animate()
实际上会运行两次。为了解决这个问题,我使用了jQuery.stop()。由于Firefox可以使用$('html').scrollTop()
而Chrome使用$('body').scrollTop()
,所以我使用Math.max()计算增量。当鼠标释放时,该函数将自动执行,并使用clearTimeout()
和jQuery.stop()
。