在鼠标滚轮上平滑滚动

Smooth scrolling on mouse wheel?

本文关键字:平滑 滚动 鼠标      更新时间:2023-09-26

与普通的鼠标滚动速度不同,我想让它在现代浏览器中更慢、更流畅、更一致。

我已经尝试过使用一些插件,比如NiceScroll(https://nicescroll.areaaperta.com/)。

但在安装后,由于某种原因,它会出现溢出:隐藏;在我的内容上,之后无法滚动到任何位置。我不需要任何自定义设计的滚动条。我只需要在使用鼠标滚动或垂直滚动条时滚动更平滑,如下所示:

http://pervolo.com/

有人能告诉我这件事吗?我计划使用skrollr插件(https://github.com/Prinzhorn/skrollr)以及平滑滚动。

这可能会让你开始:

$(window).on('mousewheel DOMMouseScroll', function(e) {
  var dir,
      amt = 100;
  e.preventDefault();
  if(e.type === 'mousewheel') {
    dir = e.originalEvent.wheelDelta > 0 ? '-=' : '+=';
  }
  else {
    dir = e.originalEvent.detail < 0 ? '-=' : '+=';
  }      
  $('html, body').stop().animate({
    scrollTop: dir + amt
  },500, 'linear');
})

DOMMouseScrolle.originalEvent.detail是Firefox所必需的。将amt更改为您想要的滚动距离,将500更改为您需要的滚动速度。

Fiddle:http://jsfiddle.net/utcsdyp1/1

我成功地使鼠标滚轮滚动看起来像黄油一样光滑!复制粘贴以下片段,然后自己尝试。

let easeInOutQuint = t => t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t; // Easing function found at https://gist.github.com/gre/1650294
// With this attempt I tried to make the scroll by mouse wheel look smooth
let delay = ms => new Promise(res => setTimeout(res, ms));
let dy = 0;
window.addEventListener("wheel", async e => {
    // Prevent the default way to scroll the page
    e.preventDefault();
    dy += e.deltaY;
    let _dy = dy; // Store the value of "dy"
    await delay(150); // Wait for .15s
    // If the value hasn't changed during the delay, then scroll to "start + dy"
    if (_dy === dy) {
        let start = window.scrollY || window.pageYOffset;
        customScrollTo(start + dy, 600, easeInOutQuint);
        dy = 0;
    }
}, { passive: false });
function customScrollTo(to, duration, easingFunction) {
    let start = window.scrollY || window.pageYOffset;
    let time = Date.now();
    let timeElapsed = 0;
    let speed = (to - start) / duration;
    
    (function move() {
        if (timeElapsed > duration) {
            return;
        }
        timeElapsed = Date.now() - time;
        // Get the displacement of "y"
        let dy = speed * timeElapsed;
        let y = start + dy;
        // Map "y" into a range from 0 to 1
        let _y = (y - start) / (to - start);
        // Fit "_y" into a curve given by "easingFunction"
        _y = easingFunction(_y);
        // Expand "_y" into the original range
        y = start + (to - start) * _y;
        window.scrollTo(0, y);
        window.requestAnimationFrame(move);
    })();
}

当用户使用$(element).on( "scroll", handler )滚动时,您可以捕捉到一个操作,然后,例如,使用以下代码

$('html, body').animate({
    scrollTop: $("#target-element").offset().top
}, 1000);

使用jQuery 滚动到某个元素