DOM & BOM – MutationObserver
介绍
它和 IntersectionObserver, ResizeObserver 差不多, 都是观察 element 变化的.
它可以观察元素的 attribute 增加, 移除, 修改, append child 等等.
建议先看前 2 篇 和 一起了解会比较容易.
new MutationObserver()
const mo = new MutationObserver((mutations) => { console.log("mutations", mutations); }); mo.observe(document.querySelector(".container"), { attributes: true, });
调用方式和 Intersection, ResizeObserver 是一样的.
注意: 它和 IO 和 Resize 有个区别, IO, Resize 调用 observe 第一次会马上触发掉, 但 Mutation 没有, 它会等到真的有改变时才触发.
还有一个特别之处是 observe 的时候需要一个 config. 指定要观察的范围.
出于性能考虑, 观察的范围越广性能越伤, 所以请按需设置哦.
观察 attributes
attributes: true
可以观察到元素添加, 移除, 修改 attribute.
attributeOldValue: true
多了一个 oldValue
attributeFilter: ["contenteditable"]
指定要观察的 attribute, 没有在 list 里面的, 添加, 移除, 修改都不会触发.
观察 Child 和 Descendant Element
childList: true
当元素 appendChild / removeChild 的时候触发.
subtree: true
当元素有子孙后裔插入或移除时触发.
观察 TextNode textcontent
characterData: true & characterDataOldValue: true
const textNode = document.createTextNode("Hello World"); mo.observe(textNode, { characterData: true, characterDataOldValue: true }); setTimeout(() => { textNode.textContent = "SuperMan"; }, 3000);
效果
注意, 一定要是 TextNode 哦.
const p = document.createElement("p"); p.textContent = "Hello World"; mo.observe(p, { characterData: true, characterDataOldValue: true }); setTimeout(() => { p.textContent = "SuperMan"; document.body.append(p); }, 3000);
换成 p 就不灵了.
虽然 p 是有效的, 可以 append to body 看到字, 但是 observer 没有监听到它. 所以监听的节点一定要是 TextNode.