首頁 > web前端 > css教學 > 彈性溢出滾動

彈性溢出滾動

William Shakespeare
發布: 2025-03-08 12:00:19
原創
553 人瀏覽過

Elastic Overflow Scrolling

許多移動設備都具備一種類似橡皮筋的滾動效果,允許用戶滾動超出視口邊緣一段距離,鬆手後頁面會回彈到原位。 這種效果在大多數瀏覽器中自動實現,例如iOS Safari。 然而,實現這種“橡皮筋”滾動效果,且兼容非觸摸設備,並非易事。 CSS中並沒有直接的屬性來控制此效果,雖然存在非標準的 -webkit-overflow-scrolling 屬性,但它用於不同的動量滾動。

如果需要強制實現這種橡皮筋效果,通常需要使用JavaScript添加滾動監聽器或組合使用 pointerDownpointerUppointerMove 事件,並跟踪位置和慣性運動等。但這較為複雜。

理想情況下,我們希望使用純CSS解決方案。

考慮一個包含多個子元素的容器:

<div>
  <div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
  </div>
</div>
登入後複製

首先,設置一些基礎樣式,確保父容器溢出:

/* 父容器,设置固定尺寸以产生溢出 */
.carousel {
  width: 200px;
  height: 400px;
  overflow-x: hidden;
  overflow-y: auto;
}

/* 子元素容器,垂直排列 */
.slides {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  width: 100%;
  height: fit-content;
}

/* 每个子元素占据容器全宽 */
.slide {
  width: 100%;
  aspect-ratio: 1;
}
登入後複製

關鍵在於為子元素添加垂直邊距。如果容器只有一個長元素,則在該元素的頂部和底部添加邊距;如果有多個子元素,則在第一個元素的頂部和最後一個元素的底部添加邊距:

.carousel > .slides > .slide:first-child {
  margin-top: 100px;
}

.carousel > .slides > .slide:last-child {
  margin-bottom: 100px;
}
登入後複製

這樣,我們就可以滾動超出邊緣了。為了實現回彈效果,我們需要使用 scroll-snap-typescroll-snap-align 屬性:

.carousel {
  scroll-snap-type: y mandatory;
}

.carousel > .slides > .slide {
  scroll-snap-align: start;
}

.carousel > .slides > .slide:first-child {
  margin-top: 100px;
}

.carousel > .slides > .slide:last-child {
  scroll-snap-align: end;
  margin-bottom: 100px;
}
登入後複製

對於水平滾動元素,只需將邊距應用於元素的左右邊緣,並將 scroll-snap-type 屬性的值從 y mandatory 更改為 x mandatory

這就是全部!這是一個簡潔有效的純CSS解決方案。

相關資源:

  • “The inside story of the iconic ‘rubber band’ effect that launched the iPhone” (Cult of Mac)
  • “Six things I learnt about iOS Safari’s rubber band scrolling” (Special Agent Squeaky)
  • “Scroll Bouncing On Your Websites” (Smashing Magazine)

以上是彈性溢出滾動的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板