除了正常的鼠标滚动速度之外,我还想让它更慢,更流畅,并且在现代浏览器中保持一致。
我已经尝试过使用一些像NiceScroll(https://nicescroll.areaaperta.com/)这样的插件。
但是在安装之后,由于某种原因它会出现溢出:隐藏;在我的内容上,无法在任何地方滚动。我不需要任何自定义设计的滚动条。我只需要在使用鼠标滚动或垂直滚动条时滚动更平滑:
有人可以请教我这个吗?我打算使用skrollr插件(https://github.com/Prinzhorn/skrollr)和平滑滚动。
答案 0 :(得分:5)
这可能会让你前进:
$(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');
})
Firefox需要 DOMMouseScroll
和e.originalEvent.detail
。将amt
更改为您想要的滚动距离,并将500
更改为您想要的滚动速度。
答案 1 :(得分:0)
当用户使用$(element).on( "scroll", handler )
滚动时,您可以捕获操作,然后使用例如此代码
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
使用jQuery滚动到某个元素
答案 2 :(得分:0)
我成功地让鼠标滚轮的滚动看起来像黄油一样光滑!复制粘贴以下代码片段并自己尝试。
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);
})();
}