如何用纯 css 实现页面滚动停靠效果

如何用纯 css 实现页面滚动停靠效果

效果图

以前要实现页面滚动停靠效果需要借助 js 来操作 dom,类似于fullpage.js插件,现在纯 css 也能做到同样的事。

scroll-snap-type

scroll-snap-type 属性定义元素容器的滚动方式。该属性不能作用于body标签(我用的时候不可用)。

属性

none | [ x | y | block | inline | both ] [ mandatory | proximity ]?
  • x:x 轴;
  • y:y 轴;
  • both:x 轴 与 y 轴
  • mandatory:可选,强制滚动,只要发生滚动就滚到下一页;
  • proximity:可选,协商滚动,滚动大半才滚动到下一页,否则留在当前滚动点或回滚当前页(不怎么好使)。

scroll-snap-align

scroll-snap-align属性指定元素相对容器的滚动方向对齐方式。可以作用于容器子孙元素。

属性

  • start:头部对齐;
  • center:居中对齐;
  • end:尾部对齐。

示例

html 核心代码

<div class="container">
  <div class="box" style="background-color: brown;">内容1</div>
  <div class="box" style="background-color:blueviolet">内容2</div>
  <div class="box" style="background-color:blue;">内容3</div>
  <div class="box" style="background-color:aqua;">内容4</div>
  <div class="box" style="background-color:burlywood;">内容5</div>
</div>

css 核心代码

.container {
  overflow: hidden auto;
  width: 100vw;
  height: 100vh;
  scroll-snap-type: y mandatory;
}

.box {
  width: 100vw;
  height: 100vh;
  scroll-snap-align: center;
}

注意事项

以上代码在移动表现良好,在桌面端滑动略有卡顿感,需要在容器添加will-change: scroll-position属性。

posted @   梦渊同学  阅读(720)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示