大网数据广告活动
Web 标准与前端开发

Document: scrollsnapchanging event

· 52CE 我爱测

The **`scrollsnapchanging`** event of the Document interface is fired on the scroll container when the browser determines a new scroll snap target is pending, i.e., it will be selected when the current scroll gesture ends.

The scrollsnapchanging event of the Document interface is fired on the scroll container when the browser determines a new scroll snap target is pending, i.e., it will be selected when the current scroll gesture ends.

This event works in much the same way as the Element interface's scrollsnapchanging event, except that the overall HTML document has to be set as the scroll snap container (i.e., scroll-snap-type is set on the html element).

Syntax

Use the event name in EventTarget/addEventListener:

addEventListener("scrollsnapchanging", (event) => { })

Alternatively, assign to the event handler property of the interface:

onscrollsnapchanging = (event) => { }

Event type

A SnapEvent, which inherits from the generic Event type.

Examples

Basic usage

Let's say we have a main element containing significant content that causes it to scroll:

<main>
  
</main>

The <main> element can be turned into a scroll container using a combination of CSS properties, for example:

main {
  width: 250px;
  height: 450px;
  overflow: scroll;
}

We can then implement scroll snapping behavior on the scrolling content by specifying the scroll-snap-type property on the html element:

html {
  scroll-snap-type: block mandatory;
}

The following JavaScript snippet would cause the scrollsnapchanging event to fire on the HTML document when a child of the <main> element becomes a pending snap target. In the handler function, we set a pending class on the child referenced by the SnapEvent.snapTargetBlock property, which could be used to style it differently when the event fires.

document.addEventListener("scrollsnapchanging", (event) => {
  // remove previously-set "pending" classes
  const pendingElems = document.querySelectorAll(".pending");
  pendingElems.forEach((elem) => {
    elem.classList.remove("pending");
  });

  // Set current pending snap target class to "pending"
  event.snapTargetBlock.classList.add("pending");
});

At the start of the function, we select all elements that previously had the pending class applied and remove it, so that only the most recent pending snap target is styled.

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。