zoukankan      html  css  js  c++  java
  • MutationObserver监听DOM变化

    MutationObserver介绍

      当我们想想监听某个DOM发生了更改,可以使用MutationObserver,该API被所有现代浏览器支持。

    构造方法

    MutationObserver()

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

    方法

    disconnect()

      阻止 MutationObserver 实例继续接收的通知,直到再次调用其observe()方法,该观察者对象包含的回调函数都不会再被调用。

    observe()

      配置MutationObserver在DOM更改匹配给定选项时,通过其回调函数开始接收通知。

    takeRecords()

      从MutationObserver的通知队列中删除所有待处理的通知,并将它们返回到MutationRecord对象的新Array中。

    MutationObserver用法

    // Select the node that will be observed for mutations
    var targetNode = document.getElementById('some-id');
    
    // Options for the observer (which mutations to observe)
    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) {
            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();

    配置

    • childList:子元素的变动,Boolean
    • attributes:属性的变动,Boolean
    • characterData:节点内容或节点文本的变动,Boolean
    • subtree:所有下属节点(包括子节点和子节点的子节点)的变动,Boolean
    • attributeFilter: 监听制定属性[attrName],Array 如["class",  "src"]

    如果config只配置了attributes: true, childList: true,没有配置subtree: true,那么只能监听当前目标,如果有属性变化或者子元素(只监控一级子元素,子元素的子元素不监控)增删。

    如果配置了subtree: true,则可以监控目标元素下的所有子元素(递归所有子子元素)。如果目标元素下有多个变化,比如属性变化,子元素变化,则会在所有变化完成后再调用回调函数。回调函数在线程事件队列的一个执行栈执行完毕后触发,如果在下一个执行栈中继续有DOM变化则再次触发回调函数(比如在新增DOM后设置setTimeout 0秒后再新增dom,则会触发两次回调)。

    引申

      目前js没有直接监控重绘事件的API,MutationObserver在某种意义上可作为监听重绘事件能力比较接近的方法。如果小伙伴有可以监控重绘事件的办法,欢迎留言,多多讨论。

    参考:https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver

  • 相关阅读:
    01:oracle sql developer配置
    删除eclipse或者MyEclipse的workspace记录
    c++特殊函数
    java类和对象的基础(笔记)
    java打印日历
    10_9 java笔记
    程序流程
    学习疑惑……
    位运算和逻辑运算
    多种类型的指针
  • 原文地址:https://www.cnblogs.com/bagexiaowenti/p/12764720.html
Copyright © 2011-2022 走看看