使用 MutationObserver API實時監聽DOM元素變化
創建 MutationObserver 實列,接受一個用于監聽到DOM元素變化的回調函數
const handleListenChange = (mutationsList, observer) => {console.log(mutationsList, observer)
}
const mutationObserver = new MutationObserver(handleListenChange)
mutationsList
為DOM元素所有變化的列表集合,列表元素包含以下屬性
- type:元素變化類型(attribute、characterData、childList…)。
- target:發生變動的DOM節點。
- addedNodes:新增的DOM節點。
- removedNodes:刪除的DOM節點。
- previousSibling:前一個同級節點,如果沒有則返回null。
- nextSibling:下一個同級節點,如果沒有則返回null。
- attributeName:發生變動的屬性。如果設置了attributeFilter,則只返回預先指定的屬性。
- oldValue:變動前的值。這個屬性只對attribute和characterData變動有效,如果發生childList變動,則返回null。
開啟監聽
const element = document.querySelector('#')
const options = {attributes: true,childList: true,subtree: true
}
mutationObserver.observe(element, options)
element
為需要監聽的DOM對象
options
為需要監聽該DOM對象哪些變化,有以下幾種
- childList:子節點的變動(指新增,刪除或者更改)。
- attributes:屬性的變動。
- characterData:節點內容或節點文本的變動。
- subtree:布爾值,表示是否將該觀察器應用于該節點的所有后代節點。
- attributeOldValue:布爾值,表示觀察attributes變動時,是否需要記錄變動前的屬性值。
- characterDataOldValue:布爾值,表示觀察characterData變動時,是否需要記錄變動前的值。
- attributeFilter:數組,表示需要觀察的特定屬性(比如
['class','src']
)。
停止監聽
mutationObserver.disconnect();
清除變動記錄并返回記錄值
const changes = mutationObserver.takeRecords();
console.log(changes);