【发布时间】:2020-03-03 07:14:41
【问题描述】:
我有一个完全水平展开的页面,可以通过按例如空格键、Page Down、右箭头来滚动, Home、End 等进行导航。
我目前有两个问题想要解决:
当按下 右箭头 或 左箭头 键时,页面移动略大于 100vw,但目标是完美对齐页面边缘与窗户。
例如,如果您在到达页面末尾时多次按下 Page Down 键,那么您将获得相同数量的 Page Up 按下可向后滚动。
如果能帮助我解决这个问题,我将不胜感激。
这是我的代码:
let scrollAmount = 0
const container = document.documentElement
window.onload = () => {
document.body.onkeyup = event => {
switch (event.code) {
case "Space":
case "PageDown":
case "ArrowRight": {
scrollAmount += window.innerWidth
break
}
case "PageUp":
case "ArrowLeft": {
scrollAmount -= window.innerWidth
break
}
case "Home":
case "ArrowUp": {
scrollAmount = 0
break
}
case "End":
case "ArrowDown": {
scrollAmount = container.scrollWidth
break
}
}
container.scrollTo({
top: 0,
left: scrollAmount,
behavior: "smooth"
})
}
}
// Reset the scrollAmount if the user scrolls back manually.
window.onscroll = event => {
scrollAmount = container.scrollLeft
}
* {
margin: 0;
padding: 0
}
html { height: 100% }
html, body, section {
display: flex;
flex-grow: 1
}
body {
scroll-snap-type: x mandatory;
scroll-snap-points-x: repeat(100%);
overflow-x: auto
}
section {
display: grid;
place-items: center;
flex: 1 0 100%;
scroll-snap-align: center
}
section:nth-of-type(1) { background: orange }
section:nth-of-type(2) { background: limeGreen }
section:nth-of-type(3) { background: royalBlue }
h2 { color: white }
<section><h2>1</h2></section>
<section><h2>2</h2></section>
<section><h2>3</h2></section>
【问题讨论】:
标签: javascript ecmascript-6 scroll keyboard-shortcuts