监听节点属性变化
<!DOCTYPE html> <html lang="en"> <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> <style> * { font-size: 28px; } </style> </head> <body> <div id="container"> </div> <div> <button type="button" id="btnAdd">添加子节点</button> </div> <script> const containerEl = document.getElementById('container'); // 观察器的配置(需要观察什么变动) 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. ${performance.now()}`); } else if (mutation.type === 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.'); } } }; // 创建一个观察器实例并传入回调函数 const observer = new MutationObserver(callback); // 以上述配置开始观察目标节点 observer.observe(containerEl, config); btnAdd.onclick = function () { setTimeout(function () { console.log("setTimeout callback:", performance.now()); }); containerEl.append(`added node: ${performance.now()}`); } </script> </body> </html>