[英]Key presses get “remembered” when the beginning or the end of the page is reached
我有一个完全水平展开的页面,可以通过按例如Space Bar 、 Page Down 、 Right Arrow 、 Home 、 End等滚动来导航。
我遇到的问题是,例如,如果您在到达页面末尾时多次按下Page Down键,那么您将需要相同数量的Page Up按下才能向后滚动。 例如,如果您多次按左箭头,然后尝试右后记 go,则在页面开头也会发生同样的情况。
我该如何解决这个问题,以便在到达页面的开头或结尾时不会“记住”按键?
您可以在下面运行我的代码:
let scrollAmount = 0 const container = document.documentElement window.onload = () => { document.body.onkeydown = event => { switch (event.code) { case "Space": case "PageDown": case "ArrowRight": case "ArrowDown": { event.preventDefault() scrollAmount += window.innerWidth break } case "PageUp": case "ArrowLeft": case "ArrowUp": { event.preventDefault() scrollAmount -= window.innerWidth break } case "Home": { scrollAmount = 0 break } case "End": { 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 } section { display: grid; place-items: center; flex: 1 0 100% } 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>
如果您在开始或结束,添加将阻止您增加scrollAmount
的限制:
scrollAmount
为 0scrollAmount
等于body.scrollWidth - window.innerWidth
(body的整个宽度 - 一页的宽度) let scrollAmount = 0 const container = document.documentElement window.onload = () => { document.body.onkeydown = event => { switch (event.code) { case "Space": case "PageDown": case "ArrowRight": case "ArrowDown": { event.preventDefault() const maxScroll = container.scrollWidth - window.innerWidth if(scrollAmount === maxScroll) return; // if at the end, return scrollAmount += window.innerWidth break } case "PageUp": case "ArrowLeft": case "ArrowUp": { event.preventDefault() if(scrollAmount === 0) return; // if at the start return scrollAmount -= window.innerWidth break } case "Home": { scrollAmount = 0 break } case "End": { scrollAmount = container.scrollWidth - window.innerWidth 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 } section { display: grid; place-items: center; flex: 1 0 100%; } 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.