diff --git a/src/utils/index.js b/src/utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c6a513119fbfc0060ecdac0d26da1e7490d9bafb --- /dev/null +++ b/src/utils/index.js @@ -0,0 +1,41 @@ +class ListenDomChange { + constructor(dom, callbackDomChange) { + // 监听 dom 节点 + this.dom = dom; + // 回调函数 + this.callbackDomChange = callbackDomChange; + } + // 监听 dom变化 + mutationListen() { + // 选择需要观察变动的节点 + const targetNode = this.dom + + // 观察器的配置(需要观察什么变动) + const config = { attributes: true, childList: true, subtree: true }; + + // 当观察到变动时执行的回调函数 + const callback = function (mutationsList, observer) { + // Use traditional 'for loops' for IE 11 + for (let mutation of mutationsList) { + if (mutation.type === "childList") { + console.log("A child node has been added or removed."); + } else if (mutation.type === "attributes") { + console.log("The " + mutation.attributeName + " attribute was modified."); + } + } + }; + + // 创建一个观察器实例并传入回调函数 + const observer = new MutationObserver(callback); + + // 以上述配置开始观察目标节点 + observer.observe(targetNode, config); + + // 之后,可停止观察 + observer.disconnect(); + } +} + +export { + ListenDomChange +} \ No newline at end of file