許多移動設備都具備一種類似橡皮筋的滾動效果,允許用戶滾動超出視口邊緣一段距離,鬆手後頁面會回彈到原位。 這種效果在大多數瀏覽器中自動實現,例如iOS Safari。 然而,實現這種“橡皮筋”滾動效果,且兼容非觸摸設備,並非易事。 CSS中並沒有直接的屬性來控制此效果,雖然存在非標準的 -webkit-overflow-scrolling
屬性,但它用於不同的動量滾動。
如果需要強制實現這種橡皮筋效果,通常需要使用JavaScript添加滾動監聽器或組合使用 pointerDown
、pointerUp
和 pointerMove
事件,並跟踪位置和慣性運動等。但這較為複雜。
理想情況下,我們希望使用純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-type
和 scroll-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解決方案。
相關資源:
以上是彈性溢出滾動的詳細內容。更多資訊請關注PHP中文網其他相關文章!