2016-11-24 75 views
4

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

+0

滚动时,鼠标光标不会脱离它们按住的元素吗?如果你的意思是“点击”而不是持有,那么检查一下:[Javascript平滑滚动而不使用jQuery](https://stackoverflow.com/questions/10063380/javascript-smooth-scroll-without-the-use -jquery)或[this](https://www.sitepoint.com/smooth-scrolling-vanilla-javascript/) –

+0

谢谢,但它会是一个固定的元素,他们按住 –

回答

2

在这里你可以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 Demo

我针对$('html, body'),这样它会在Firefox和Chrome浏览器。这有点棘手,因为animate()实际上运行两次,因为两个选择器。为了解决这个问题,我使用了jQuery.stop()。由于Firefox可以使用$('html').scrollTop()而Chrome使用$('body').scrollTop(),我使用Math.max()来计算增量。该功能在完成时自行执行,并在释放鼠标时使用clearTimeout()jQuery.stop()

+0

工程很好,谢谢!有没有办法让它更平滑些? –

+0

@ScottHunter在默认的jQuery库中增加了一些补充脚本。实际上只有3种设置:线性,摆动和默认设置。您可以找到创建更平滑过渡的脚本。 – Daerik

相关问题