[英]Horizontally scrolling by a full page on key press
我有一個完全水平展開的頁面,可以通過按例如Space Bar 、 Page Down 、 Right Arrow 、 Home 、 End等滾動來導航。
我目前有兩個想解決的問題:
當按下右箭頭或左箭頭鍵時,頁面移動略大於 100vw,但其目標是使頁面邊緣與 window 完美對齊。
例如,如果您在到達頁面末尾時多次按下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>
添加event.preventDefault()
並將偵聽器更改為keydown
而不是keyup
將阻止箭頭鍵的默認連續滾動。 這是有效的,因為箭頭鍵滾動是在按住時觸發的(我們現在已經阻止了),而事件偵聽器僅在抬起箭頭鍵時才被觸發。
您可以對Home和End執行相同操作(即添加event.preventDefault()
)以防止所有水平滾動。
let scrollAmount = 0 const container = document.documentElement window.onload = () => { document.body.onkeydown = event => { // <----------- switch (event.code) { case "Space": case "PageDown": case "ArrowRight": { event.preventDefault(); // <----------- scrollAmount += window.innerWidth break } case "PageUp": case "ArrowLeft": { event.preventDefault(); // <----------- 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, }) } } // 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.