MutationObserver 监视DOM树的更改

mutationObserver 监视DOM树的更改(用处少,了解下就好)

构造函数

MutationObserver()
创建并返回一个新的  MutationObserver 它会在指定的DOM发生变化时被调用。

方法

disconnect()
阻止 MutationObserver 实例继续接收的通知,直到再次调用其 observe()方法,该观察者对象包含的回调函数都不会再被调用。
observe()
配置 MutationObserver在DOM更改匹配给定选项时,通过其回调函数开始接收通知。
takeRecords()
从MutationObserver的通知队列中删除所有待处理的通知,并将它们返回到 MutationRecord对象的新 Array中。
案例:
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6   <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7   <title>Document</title>
 8   <style>
 9     .fontColor {
10       color: pink;
11     }
12   </style>
13 
14 </head>
15 
16 <body>
17   <ul id="myList">
18     <li id='listOne'>Coffee</li>
19     <li>Tea</li>
20     <li>Milk</li>
21   </ul>
22   <button onclick="myFunction()">移除列表的第一项</button>
23   <button onclick="myFunction2()">溢出属性</button>
24   <button onclick="myFunction3()">添加class、style</button>
25   
26   <script>
27     var targetNode = document.getElementById('myList');
28 
29     var config = { attributes: true, childList: true, subtree: true };
30 
31     var callback = function (mutationsList) {
32       for (var mutation of mutationsList) {
33         if (mutation.type == 'childList') {
34           console.log('A child node has been added or removed.');
35         }
36         else if (mutation.type == 'attributes') {
37           console.log('The ' + mutation.attributeName + ' attribute was modified.');
38         }
39       }
40     };
41 
42     var observer = new MutationObserver(callback);
43 
44     observer.observe(targetNode, config);
45 
46 
47     function myFunction() {
48       var myList = document.getElementById("myList");
49       var listOne = document.getElementById("listOne");
50       myList.removeChild(listOne);
51     }
52 
53     function myFunction2() {
54       var myList = document.getElementById("myList");
55       myList.removeAttribute('lee');
56     }
57 
58     function myFunction3() {
59       var myList = document.getElementById("myList");
60       myList.classList = ['fontColor'];
61       myList.style.color = 'pink'
62     }
63   </script>
64 </body>
65 
66 </html>

猜你喜欢

转载自www.cnblogs.com/Lee242050/p/12023367.html