使用scroll-snap实现吸附效果

这篇文章发表于 阅读 0

有时我们希望在页面滚动时放开鼠标后自动回到原始位置,就是常说的吸附效果;如下: 在这里插入图片描述 上面的演示中页面自动回到了起始位置。

  1. 先看一个普通的页面滚动效果:
鼠标放开之后,页面就停留在滚动后的位置。
  1. 设置scroll-snap-type后的效果
当模块1的滚动距离小于一半时,会自动回到模块1的起始位置,超过一半时自动定位到模块2的起始位置。

代码如下。 css:

.list {
    display: flex;
    flex-direction: row;
    overflow: auto;
    white-space: nowrap;
    scroll-snap-type: x mandatory;
}
.content {
    flex-wrap: 0;
    flex-shrink: 0;
    height: 100px;
    width: 300px;
    scroll-snap-align: start;
    display: inline-block;
    text-align: center;
    font-size: 48px;
}

html:

<div class="list"> <div class="content">1</div> <div class="content">2</div> <div class="content">3</div> <div class="content">4</div> <div class="content">5</div> </div>

语法介绍

scroll-snap-type

  • none: 默认值,忽略捕捉位置
  • x: 仅捕捉水平轴上的定位点
  • y: 仅捕捉垂直轴上的定位点
  • block: 仅捕捉其块轴上的定位点
  • inline: 近捕捉内联轴方向上的定位点
  • both: 捕捉水平轴和垂直轴上的定位点
  • mandatory: 容器的可视视图将“强制”静止在临时点上,无论是添加、删除、移动或者大小改变。
  • proximity: 如果它当前没有被滚动,这个滚动容器的可视视图将基于基于用户代理滚动的参数去到临时点上。如果内容被添加、移动、删除或者重置大小,滚动偏移将被调整为保持静止在临时点上。

scroll-snap-type: x

scroll-snap-type: y

下面是值为y的效果

scroll-snap-type: block

scroll-snap-type: inline

scroll-snap-type: both

scroll-snap-align

这个属性作用在子元素上。

  • none: 不定义捕捉位置
  • start: 起始位置对其
  • end: 结束为止对其
  • center: 子元素的中心与容器的中心对齐。
scroll-snap-align: none;
scroll-snap-align: start end; /start: 表示块元素方向的定位方式,end: 表示内联元素的定位方式。/
scroll-snap-align: center;

上面的所有例子都是 scroll-snap-align: start;下面演示 endcenter的效果

scroll-snap-align: end

吸附效果都不再是元素的开头,而是出现在元素的结尾

scroll-snap-align: center

将子元素的中心与容器的中心点对齐