监听整个页面上的DOM树变化

在线预览

方法

网上查到的很多都是使用Mutation events的,但在MDN上一查这个事件已经废弃了,并且推荐用MutationObserver替换掉

Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Mutation events provide a mechanism for a web page or an extension to get notified about changes made to the DOM. Use Mutation Observers instead if possible.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1>下述方法也可以监听使用《谷歌页面翻译》时的DOM变化</h1>
  <h1>The following way also can catch changes of DOM when using <em>Google page translation</em></h1>
  <h3>使用MutationObserver(Using MutationObserver)</h3>
  <div id="hello"><span>Hello</span> <em>Mr.</em> Word!</div>
  <button onclick="addNode()">添加(add DOM)</button>
  <script>
    // Select the node that will be observed for mutations
    var targetNode = document.querySelector('body');

    // Options for the observer (which mutations to observe)
    // subtree:是否监听子节点的变化
    var config = { attributes: true, childList: true, subtree:true};

    // Callback function to execute when mutations are observed
    var callback = function(mutationsList) {
        for(var mutation of mutationsList) {
            console.log(mutation);
            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.');
            }
        }
    };

    // Create an observer instance linked to the callback function
    var observer = new MutationObserver(callback);

    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);

    // // Later, you can stop observing
    // observer.disconnect();

    var addNode = function(){
      var divnode = document.createElement("div");
      var textNode = document.createTextNode("Hello world!");
      divnode.appendChild(textNode);
      document.getElementById('hello').appendChild(divnode)
    }
  </script>
</body>
</html>

转载于:https://www.cnblogs.com/jffun-blog/p/8419919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值