MutationObserver() 与 DOMNodeInserted [重复]

问题描述 投票:0回答:1

我无法集中注意力

MutationObserver()
。 我有一个使用
DOMNodeInserted
的旧代码片段,它已被折旧。

以下为缩小图。

示例

       var d = $(document);

       // DOM Injection/Addition
       d.on('DOMNodeInserted', '*', function (e) {
           $('.ct-cont'    , e.target).addClass('bg-light m-0 p-0 w-100')
           $('.fa-solid'   , e.target).addClass('fa-fw')
           $('.ct-input'   , e.target).css('font-family', 'Courier New');
           return false;
       });

任何帮助都将受到赞赏和奖励。

javascript jquery mutation-observers
1个回答
0
投票

要用现代高效的 MutationObserver 替换已弃用的 DOMNodeInserted,您可以按如下方式重写代码。 MutationObserver 侦听 DOM 中的更改,并提供对要观察的突变类型的详细控制。

具体操作方法如下:

使用 MutationObserver 更新代码 JavaScript

// Select the node to observe (e.g., the whole document body)
const targetNode = document.body;

// Create a callback function to process DOM changes
const mutationCallback = (mutationsList, observer) => {
    for (let mutation of mutationsList) {
        if (mutation.type === 'childList') {
            // Loop through added nodes
            mutation.addedNodes.forEach((node) => {
                if (node.nodeType === Node.ELEMENT_NODE) { // Ensure it's an element
                    // Apply styles or classes to relevant elements
                    $(node).find('.ct-cont').addClass('bg-light m-0 p-0 w-100');
                    $(node).find('.fa-solid').addClass('fa-fw');
                    $(node).find('.ct-input').css('font-family', 'Courier New');
                }
            });
        }
    }
};

// Create a MutationObserver instance
const observer = new MutationObserver(mutationCallback);

// Configure the observer options
const observerOptions = {
    childList: true, // Watch for added or removed children
    subtree: true    // Include all child elements within the target node
};

// Start observing the target node
observer.observe(targetNode, observerOptions);

// To disconnect the observer when it's no longer needed
// observer.disconnect();

代码解释 变异观察者:

这是用于观察 DOM 变化的现代 API。它取代了 DOMNodeInserted 等已弃用的事件。 突变回调:

此函数处理更改。它循环遍历观察者提供的mutationsList并检查childList突变(当添加或删除节点时)。 添加节点:

对于每个变更,它都会检查addedNodes(添加到DOM 的元素)。 find() 方法用于将样式/类应用于所添加节点的相关子节点。 目标节点:

document.body是观察到的节点。如果需要,您可以将其替换为更具体的容器。 观察者选项:

childList: true:检测何时添加或删除子元素。 subtree: true:确保观察者也观察后代节点的变化。 MutationObserver 的主要优点: 更好的性能:与 DOMNodeInserted 不同,MutationObserver 针对性能进行了优化,可以高效处理高频 DOM 更改。 详细控制:可以观察特定类型的突变(属性、childList、子树等)。 现代标准:现代浏览器(IE 除外)完全支持。 测试代码 动态添加元素:通过向 DOM 动态添加元素进行测试:

javascript

const newDiv = document.createElement('div');
newDiv.className = 'ct-cont';
document.body.appendChild(newDiv);

检查更改:MutationObserver 将检测新添加的元素并自动应用类和样式。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.