前言
在做公司专题的时候,需求需要我监听DOM变化,然后做出相对应的处理,我启动我的超级大脑搜索之后,终于找到 MutationObserver
这个 API
MutationObserver
提供了监视对DOM树所做更改的能力。它被设计为旧的Mutation Events功能的替代品,该功能是DOM3 Events规范的一部分。(摘自MDN)
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
let targetNode = document.querySelector(`#id`);
let config = { attributes: true, childList: true, subtree: true };
const mutationCallback = (mutationsList) => { for(let mutation of mutationsList) { let type = mutation.type; switch (type) { case "childList": console.log("A child node has been added or removed."); break; case "attributes": console.log(`The ${mutation.attributeName} attribute was modified.`); break; case "subtree": console.log(`The subtree was modified.`); break; default: break; } } };
let observer = new MutationObserver(mutationCallback);
observer.observe(targetNode, config);
observer.disconnect();
|
又水了一篇了,罪过罪过
评论加载中