源码
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var targetNode = document.querySelector("body"); var observerOptions = { childList: true, // 观察目标子节点的变化,是否有添加或者删除 attributes: true, // 观察属性变动 subtree: true // 观察后代节点,默认为 false } var observer = new MutationObserver(function(mutationList, observer) { mutationList.forEach((mutation) => { console.log(mutation) }); console.log(observer) }); observer.observe(targetNode, observerOptions); /** * 创建节点 */ const createEl = () => { let el = document.createElement('div'); el.className = 'preRenderContainer' el.append(new Text('我是动态添加的节点')); document.body.append(el) } /** * 删除节点 */ const deleteEl = () => { document.getElementsByClassName('preRenderContainer')[0].remove(); } </script> <button onclick="createEl()">创建DOM</button> <button onclick="deleteEl()">删除DOM</button> </body> </html>
效果图
标签:el,observer,DOM,JS,var,节点,document,监听 From: https://www.cnblogs.com/bxmm/p/17221405.html