javascript - 同时使用键盘事件进行滚动和 CSS 滚动捕捉时发生冲突
问题描述
您可以按Space Bar,Page Up / Page Down和Left Arrow / Right Arrow键水平滚动我的演示页面。您还可以使用鼠标或触控板捕捉滚动。
但只有一种或另一种有效。
有没有办法让键盘事件和 CSS 滚动捕捉可以共存?我错过了什么?任何帮助将不胜感激,因为我已经为这个问题苦苦挣扎了一个多星期。
(请取消注释相关的 CSS 代码以启用滚动捕捉效果,以查看键盘快捷键停止工作。)
import animate from "https://cdn.jsdelivr.net/npm/animateplus@2/animateplus.js"
const sections = Array.from(document.querySelectorAll("section")).sort(
(s1, s2) => {
return s1.getBoundingClientRect().left - s2.getBoundingClientRect().left
}
)
const getSectionInView = () => {
const halfWidth = window.innerWidth / 2
const index = sections.findIndex(
section =>
section.getBoundingClientRect().left <= halfWidth &&
section.getBoundingClientRect().right > halfWidth
)
return index
}
const getNextSection = dir => {
const sectionInViewIndex = getSectionInView()
const nextIndex = sectionInViewIndex + dir
const numSections = sections.length
const nextSectionIndex =
nextIndex < 0 || nextIndex >= numSections ? sectionInViewIndex : nextIndex
return sections[nextSectionIndex]
}
const container = document.scrollingElement
const animateScroll = dir => {
const from = container.scrollLeft
const { left } = getNextSection(dir).getBoundingClientRect()
return progress => (container.scrollLeft = from + progress * left)
}
window.onload = () => {
document.body.onkeydown = event => {
switch (event.key) {
case " ": // Space Bar
case "PageDown":
case "ArrowRight": {
animate({
easing: "out-quintic",
change: animateScroll(1)
})
break
}
case "PageUp":
case "ArrowLeft": {
animate({
easing: "out-quintic",
change: animateScroll(-1)
})
break
}
}
}
}
注意:我正在使用一个名为Animate Plus的小而优雅的模块来实现平滑的滚动动画。
更新:@Kostja 的解决方案适用于 Chrome,但不适用于 Mac 或 iOS 的 Safari,它在 Safari 中适用对我来说至关重要。
解决方案
我想没有,css覆盖了javascript。但是您可以简单地添加轮事件侦听器,例如:
window.addEventListener("wheel", function() {
if(event.deltaY > 0){
animate({
easing: "out-quintic",
change: animateScroll(1)
})
}
if(event.deltaY < 0){
animate({
easing: "out-quintic",
change: animateScroll(-1)
})
}
});
推荐阅读
- python - BeautifulSoup 和 Selenium:从页面下载文件
- vba - MS Access 过滤器问题 - 来自两个不同下拉列表的两个标准
- flutter - Flutter Firestore,ShowTimePicker 无效参数:“TimeOfDay”错误的实例
- javascript - 有没有办法让选项卡式 pdf 显示在 Edge 中工作?
- c++ - 如何将智能指针用于动态数组?
- html - 垂直对齐具有混合内容的 HTML 按钮
- c - 仅使用扩展名搜索文件名
- android - 按下后退按钮后选项卡布局中的片段为空白
- java - 为什么 JMS 的“createTextMessage”会抛出带有字符串变量参数的异常,而不是在文字字符串上?
- windows - 在 Windows 10 中创建系统还原点