scroll-snap-stop

Baseline 2019

Newly available

Since July 2019, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

CSS 属性 scroll-snap-stop 定义了滚动容器是否可“越过”吸附位置。

尝试一下

语法

css
/* 关键字值 */
scroll-snap-stop: normal;
scroll-snap-stop: always;

/* 全局值 */
scroll-snap-stop: inherit;
scroll-snap-stop: initial;
scroll-snap-stop: revert;
scroll-snap-stop: revert-layer;
scroll-snap-stop: unset;

取值

normal

在滚动此元素的滚动容器的可见视口时,滚动容器可“越过”吸附位置。

always

滚动容器不得“越过”吸附位置,必须吸附至此元素的第一个吸附位置。

形式定义

初始值normal
适用元素all elements
是否是继承属性
计算值as specified
Animation typediscrete

形式语法

scroll-snap-stop = 
normal |
always

示例

设置不同的吸附定格

下列示例演示了 scroll-snap-stop 的值 alwaysnormal 之间的对比。当 scroll-snap-type 属性被设置为 mandatory 时——即此示例所使用的设置——scroll-snap-stop 的两值之间的区别更为明显。

HTML

html
<p>scroll-snap-stop: always(x 轴强制)</p>
<div class="x mandatory-scroll-snapping always-stop">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

<p>在奇数位子元素上 scroll-snap-stop: always(x 轴强制)</p>
<div class="x mandatory-scroll-snapping always-stop-odd">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

<p>在偶数位子元素上 scroll-snap-stop: always(x 轴强制)</p>
<div class="x mandatory-scroll-snapping always-stop-even">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

<p>scroll-snap-stop: normal(x 轴强制)</p>
<div class="x mandatory-scroll-snapping normal-stop">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

<p>scroll-snap-stop: always(y 轴强制)</p>
<div class="y mandatory-scroll-snapping always-stop">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

<p>scroll-snap-stop: normal(y 轴强制)</p>
<div class="y mandatory-scroll-snapping normal-stop">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

CSS

css
/* 在父元素上设定强制滚动吸附 */
.x.mandatory-scroll-snapping {
  scroll-snap-type: x mandatory;
}

.y.mandatory-scroll-snapping {
  scroll-snap-type: y mandatory;
}

/* 在子元素上定义滚动吸附对齐方式 */
div > div {
  scroll-snap-align: center;
}

/* 在子元素上定义滚动吸附定格 */
.always-stop > div {
  scroll-snap-stop: always;
}

.always-stop-odd > div:nth-of-type(odd) {
  scroll-snap-stop: always;
}

.always-stop-even > div:nth-of-type(even) {
  scroll-snap-stop: always;
}

.normal-stop > div {
  scroll-snap-stop: normal;
}

结果

在下方的 x 轴盒和 y 轴盒中分别从左往右和从上往下滚动。在 scroll-snap-stop 属性被设置为 always 的 x 轴盒和 y 轴盒中,即使快速滚动,滚动也将被强制止于吸附点。然而在 scroll-snap-stop 属性被设置为 normal 的盒子中,吸附点在快速滚动时被跳过。

若有要求,则可在滚动容器中选择总是(always)止于哪些元素。下列示例通过将奇数位和偶数为的元素设为目标对此进行了演示,可根据要求选择不同的策略。在下列示例中的第二和第三个盒子中,滚动分别不会“越过”奇数位和偶数位的元素。

规范

Specification
CSS Scroll Snap Module Level 1
# scroll-snap-stop

浏览器兼容性

BCD tables only load in the browser

参见