使用 HTML 和 CSS 建立水平滾動捕捉


為了建立水平滾動捕捉,我們將使用 scroll−snap−type 屬性來產生捕捉效果。scroll−snap−type 和 scroll−snap−align 屬性分別指定我們想要使用的捕捉行為型別和捕捉點的對齊方式。

scroll−snap−type 屬性的 "x mandatory" 值表示我們想要水平捕捉,而 scroll−snap−align 屬性的 "start" 值表示我們想要捕捉標記與每個部分的開頭對齊。

這可以使用 JavaScript 庫(如 ScrollSnap)來實現,這些庫為相同的功能提供了更高階的功能和自定義。

另一種選擇是 CSS 框架(如 Bootstrap),它們提供了用於水平滾動捕捉的內建元件,以及 CSS 網格或彈性盒佈局,以建立自動相互捕捉的水平部分。

演算法

  • 定義一個容器元素來容納可以水平滾動的部分

  • 將容器的寬度設定為其父元素寬度的 100%,高度設定為視口高度的 100%

  • 當內容溢位容器時,使用 CSS overflow−x 屬性啟用水平滾動

  • 使用 CSS scroll−snap−type 屬性啟用強制水平滾動捕捉

  • 為每個將要水平滾動的部分定義一個 section 類

  • 將每個部分的寬度設定為其父元素寬度的 100%,高度設定為視口高度的 100%

  • 將每個部分顯示為內聯塊元素,以允許使用 CSS display 屬性進行水平放置

  • 使用 CSS scroll−snap−align 屬性將每個部分的捕捉對齊方式設定為容器的開頭

示例

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Horizontal Scroll Snap</title>

    <!---------------------- CSS ---------------------------->
    <style>

      /* Set the width of the container element to 100% of its parent element's width,
      and the height to 100% of the viewport height */
        .container {
          width: 100%;
          height: 100vh;
          /* Enable horizontal scrolling when the content overflows the container */
          overflow-x: scroll;
          /* Enable mandatory horizontal scroll snapping */
          scroll-snap-type: x mandatory;
        }

        /* Set the width of each section to 100% of its parent element's width,
          and the height to 100% of the viewport height */
        .section {
          width: 100%;
          height: 100vh;
          /* Display each section as an inline block element to allow horizontal placement */
          display: inline-block;
          /* Set the snap alignment of each section to the start of the container */
          scroll-snap-align: start;
        }

    </style>

  </head>
  <body>
    <!-- The container element will contain the sections that can be scrolled horizontally -->
    <div class="container">
      <!-- Each section is wrapped inside an <h1> tag -->
      <h1><div class="section">Section 1</div></h1>
      <h1><div class="section">Section 2</div></h1>
      <h1><div class="section">Section 3</div></h1>
      <h1><div class="section">Section 4</div></h1>
    </div>
    
  </body>
  </html>

在建立此功能時,務必確保跨不同瀏覽器和裝置的相容性。應使用 CSS 屬性(如 scroll−snap−type、scroll−snap−align 和 scroll−behavior)來控制滾動捕捉行為。HTML 結構應使用容器元素和固定寬度項進行設定。應確定捕捉點,並使用 scroll−behavior 啟用平滑滾動。應提供適當的 ARIA 屬性和鍵盤導航選項。透過牢記這些注意事項和約束,開發人員可以建立功能強大且使用者友好的水平滾動捕捉。

結論

水平滾動捕捉允許使用者輕鬆瀏覽網頁的水平部分。它可以用於各種目的,例如影像滑塊、作品集、產品輪播等。

更新於: 2023年8月18日

694 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告