许多移动设备都具备一种类似橡皮筋的滚动效果,允许用户滚动超出视口边缘一段距离,松手后页面会回弹到原位。 这种效果在大多数浏览器中自动实现,例如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中文网其他相关文章!