Skip to content

滚动吸附

  1. scroll-snap-type 设置了在有滚动容器的情形下吸附至吸附点的严格程度。
    • none 在滚动此滚动容器的可见视口时,必须忽略吸附点。
    • x/y 滚动容器仅在其 横轴/纵轴 上吸附至吸附位置。
    • block/inline 滚动容器仅在其 块向轴/行向轴 上吸附至吸附位置。
    • mandatory 滚动容器必须始终在吸附点上停留。
    • proximity 滚动容器仅在吸附点上停留,但当元素在吸附点附近时,它将“越过”吸附点。
  2. scroll-snap-align 设置了滚动元素在滚动容器中的对齐方式。
    • none 此盒在此轴上未定义吸附位置。
    • start 此盒的滚动吸附区域在滚动容器的吸附口中的首对齐为此轴上的吸附位置 (当子元素不能撑满父元素时显著)。
    • end 此盒的滚动吸附区域在滚动容器的吸附口中的末对齐为此轴上的吸附位置 (当子元素不能撑满父元素时显著)。
    • center 此盒的滚动吸附区域在滚动容器的吸附口中的居中对齐为此轴上的吸附位置。
  3. scroll-snap-stop 设置了滚动元素在滚动容器中是否可“越过”吸附位置。
    • normal 在滚动此元素的滚动容器的可见视口时,滚动容器可“越过”吸附位置。
    • always 滚动容器不得“越过”吸附位置,必须吸附至此元素的第一个吸附位置。
1
2
3
4
5

提示

css
scroll-snap-align: start end; /* 当设置两值时,第一值为块向,第二值为行向 */
代码
vue
<template>
  <div class="container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
  </div>
</template>

<style>
.container {
  width: 100%;
  height: 400px;
  overflow: scroll;
  /* 设置了在有滚动容器的情形下吸附至吸附点的严格程度 */
  scroll-snap-type: y proximity;
  .item {
    width: 100%;
    height: 400px;
    font-size: 2rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    /* 滚动到该元素时,该元素居中 */
    scroll-snap-align: center;
    /* 滚动到该元素时,该元素不会重复滚动 */
    scroll-snap-stop: always;
  }
  .item:nth-child(2n + 1) {
    background-color: aquamarine;
  }
  .item:nth-child(2n) {
    background-color: burlywood;
  }
}
</style>

Released under the MIT License.