首页 > web前端 > css教程 > 弹性溢出滚动

弹性溢出滚动

William Shakespeare
发布: 2025-03-08 12:00:19
原创
557 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板