Window:scrollsnapchanging 事件
Window 介面的 scrollsnapchanging 事件會在瀏覽器確定有新的滾動吸附目標(即,在當前滾動手勢結束時將被選中的目標)待定(pending)時,在 window 物件上觸發。
此事件的運作方式與 Element 介面的 scrollsnapchanging 事件非常相似,只是需要將整個 HTML 文件設定為滾動吸附容器(即,在 <html> 元素上設定了 scroll-snap-type)。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("scrollsnapchanging", (event) => { })
onscrollsnapchanging = (event) => { }
事件型別
示例
基本用法
假設我們有一個 <main> 元素,其中包含大量會導致其滾動的內容。
html
<main>
<!-- Significant content -->
</main>
可以透過組合 CSS 屬性將 <main> 元素轉變為滾動容器,例如:
css
main {
width: 250px;
height: 450px;
overflow: scroll;
}
然後,我們可以透過在 <html> 元素上指定 scroll-snap-type 屬性,來為滾動內容實現滾動吸附行為。
css
html {
scroll-snap-type: block mandatory;
}
下面的 JavaScript 程式碼片段會在 <main> 元素的子元素成為待定的吸附目標時,在 HTML 文件上觸發 scrollsnapchanging 事件。在處理函式中,我們為由 snapTargetBlock 屬性引用的子元素設定一個 pending 類,該類可用於在事件觸發時對其進行不同的樣式設定。
js
window.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");
});
在函式開頭,我們選擇所有先前應用了 pending 類的元素並移除該類,以便只有最新的待定吸附目標會被設定樣式。
規範
| 規範 |
|---|
| CSS 滾動捕捉模組級別 2 # scrollsnapchanging |
瀏覽器相容性
載入中…
另見
scrollsnapchange事件scrollend事件SnapEvent- CSS
scroll-snap-type屬性 - CSS 滾動吸附模組
- 使用滾動捕捉事件
- developer.chrome.com 上的滾動捕捉事件 (2024)