MutationObserver - Web APIs 编辑

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

Constructor

MutationObserver()
Creates and returns a new MutationObserver which will invoke a specified callback function when DOM changes occur.

Methods

disconnect()
Stops the MutationObserver instance from receiving further notifications until and unless observe() is called again.
observe()
Configures the MutationObserver to begin receiving notifications through its callback function when DOM changes matching the given options occur.
takeRecords()
Removes all pending notifications from the MutationObserver's notification queue and returns them in a new Array of MutationRecord objects.

Mutation Observer & customize resize event listener & demo

https://codepen.io/webgeeker/full/YjrZgg/

Example

The following example was adapted from this blog post.

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(const 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
const observer = new MutationObserver(callback);

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

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

Specifications

SpecificationStatusComment
DOM
The definition of 'MutationObserver' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:176 次

字数:5313

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文