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

Element: scrollsnapchange event

· 52CE 我爱测

The **`scrollsnapchange`** event of the Element interface is fired on the scroll container at the end of a scrolling operation when a new scroll snap target has been selected, just before the corresponding Element/scrollend_event event fires.

The scrollsnapchange event of the Element interface is fired on the scroll container at the end of a scrolling operation when a new scroll snap target has been selected, just before the corresponding Element/scrollend_event event fires.

A scrolling operation ends when the user finishes scrolling within a scroll container — for example using a touch gesture or by dragging the mouse pointer on a scroll bar — and releases the gesture.

Syntax

Use the event name in EventTarget/addEventListener:

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

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

onscrollsnapchange = (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 that snaps to its children when scrolled using a combination of the CSS scroll-snap-type property and other properties. For example:

main {
  width: 250px;
  height: 450px;
  overflow: scroll;
  scroll-snap-type: block mandatory;
}

The following JavaScript snippet would cause the scrollsnapchange event to fire on the <main> element when one of its children becomes a newly-selected snap target. In the handler function, we set a selected class on the child referenced by the SnapEvent.snapTargetBlock property, which could be used to style it to look like it has been selected (for example, with an animation) when the event fires.

const scrollingElem = document.querySelector("main");

scrollingElem.addEventListener("scrollsnapchange", (event) => {
  event.snapTargetBlock.classList.add("selected");
});

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

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

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