我有一个自定义滚动条解决方案(view on CodePen)。
一个明显的想法是拖动自定义滚动条可以滚动页面。
尝试一下,看看会发生什么……这很奇怪,而且滚动条和页面滚动会突然在两点之间跳动。
滚动过程当前在mousemove
处理程序中:
window.scrollTo(...)
新位置,相对于新滚动条位置的视口top
计算如果我注释掉window.scrollTo(...)
行,那么滚动条本身就会完美平滑地移动并与光标保持一致。
相关代码
mousemove(e) {
if (!this.active) return;
this.update(this.getScrollDeltaPositional(e.pageY));
window.scrollTo({top: this.getWindowScrollTop()});
}
update(position, show=true, timer=true, time=0) {
let track = this.getTrackHeight();
this.trackPosition = Math.min(Math.max(position, 0), track);
this.track.style.transform = `translateY(${this.trackPosition}px)`;
}
getWindowScrollTop() {
let scroll = this.getDocumentScroll();
let position = (this.trackPosition / this.root.clientHeight);
return Math.round(scroll * position);
}
(建议您在CodePen上查看完整的源代码)
我假设每个mousemove
的滚动阻止mousemove
事件,从而导致观察到突然的突然变化。
如何使用自定义滚动条在window
上实现平滑滚动效果?
答案 0 :(得分:1)
在尝试了所有可能的补救措施之后,我花了很多小时才发现这个相同的问题:https://css-tricks.com/forums/topic/scrolltop-inexplicably-going-haywire/。
该用户最终发现,MouseEvent.pageY
(我用来获取滚动位置的东西)是
relative to the top edge of the viewport, including scroll offsets 。
因此,滚动运动有效地放大了mousemove
事件,从而导致滚动加速,如演示中所示。
因此,经过半天的研究,此修复程序是一个简单的Ctrl + H ...使用 MouseEvent.clientY
。