功能--监听页面元素的变化-MutationObserver

51 阅读1分钟

使用到的api  -- MutationObserver

MutationObserver - Web API 接口参考 | MDN

基本html代码

<body>
    <button onclick="addElement()">添加元素</button>
    <button onclick="deleteElement()">删除元素</button>
    <div id="father" style="width: 300px;height: 300px;background-color: red;"></div>
</body>

<script>
    let father = document.getElementById('father');
    function addElement() {
        father.innerHTML += '<div id="son" style="width: 100px;height: 100px;background-color: blue;">我是子元素</div>';
    }
    function deleteElement() {
        father.removeChild(father.lastChild);
    }
</script>

基本使用需要进行的配置

<script>
    //观察的对现象
    let father = document.getElementById('father');

    //观察器的配置(需要观察什么变动)
    const config = { childList: true };

    //回调函数(观察到变动执行的回调函数)
    const callback = function (mutationList, observer) {
        for (let mutation of mutationList) {
            if (mutation.type === 'childList') {
                console.log('子元素发生了变化');
                //停止观察
                obsever.disconnect();
            }
        }
    }

    //创建一个观察器实例并传入回调函数
    const obsever = new MutationObserver(callback);

    //开始观察已配置的目标节点
    obsever.observe(father, config);
</script>

observe方法参数说明

(观察元素,观察配置)

观察配置说明

​编辑

图片来源:MutationObserver用法总结( 监听DOM变化 )

 回调函数的参数配置

(变化的列表,observer对象)