我在网站的可滚动区域上有一个绝对定位的元素。单击此元素将向下滚动页面;它供使用隐藏滚动条且不提供良好的触摸板滚动体验的 chromebook 的学生使用。
但是,如果用户(在 Chrome 上)手动滚动,并且光标滑过绝对定位的按钮,页面将完全停止滚动。当光标悬停在按钮上时,我希望页面“正常”滚动。
捕获 wheel 事件然后创建一个新的 wheel 事件并将其分派(dispatch)给可滚动内容是行不通的,我相信是因为 .isTrusted
是 false。
作为解决方法,我正在捕获滚轮事件并在可滚动元素上手动调用 .scrollBy
。但是,这不会将页面滚动相同的距离,并且还会导致滚动不流畅、断断续续。
elemScrollImg.addEventListener('wheel', (e) => {
console.log("Img scroll: ", e)
let deltaY = e.deltaY
// Wanted to make a new WheelEvent to pass to the container
// but isTrusted is false for "fake" events, and the page
// apparently just ignores them :-/
// https://stackoverflow.com/a/44462125
elemContent.scrollBy({
top: deltaY,
left: 0,
// smooth scrolling apparently just makes it all worse,
// esp. on touchpad scrolling.
// behavior: 'smooth',
})
https://jsfiddle.net/seatag/a8m1kw20/58/
是否有推荐的方法来完成此操作?
最佳答案
我最后使用 position: sticky
将按钮放置在可滚动容器内,这允许滚轮事件正常冒泡。这没有回答我的问题,但确实解决了我的问题。
.arrowWrapper {
position: sticky;
bottom: 15px;
padding: 6px;
padding-bottom: 15px;
width: 200px;
margin-left: auto;
margin-right: auto;
cursor: pointer;
background: #f00;
}
关于javascript - 我应该如何将滚轮或滚动事件从一个元素转移到另一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663466/