JS监听DOM创建和销毁

源码

web开发指南

<!DOCTYPE html>
<html lang="zh">
    <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>
    </head>
    <body>
        <script>
            var targetNode = document.querySelector("body");
            var observerOptions = {
                childList: true, // 观察目标子节点的变化,是否有添加或者删除
                attributes: true, // 观察属性变动
                subtree: true // 观察后代节点,默认为 false
            }

            var observer = new MutationObserver(function(mutationList, observer) {
                mutationList.forEach((mutation) => {
                    console.log(mutation)
                });
                console.log(observer)
            });
            observer.observe(targetNode, observerOptions);

            /**
             * 创建节点
             */
            const createEl = () => {
                let el = document.createElement('div');
                el.className = 'preRenderContainer'
                el.append(new Text('我是动态添加的节点'));
                document.body.append(el)
            }

            /**
             * 删除节点
             */
            const deleteEl = () => {
                document.getElementsByClassName('preRenderContainer')[0].remove();
            }
        </script>
        <button onclick="createEl()">创建DOM</button>
        <button onclick="deleteEl()">删除DOM</button>
    </body>
</html>

效果图

 

posted @ 2023-03-16 10:33  天葬  阅读(645)  评论(0编辑  收藏  举报