3分钟学会使用MutationObserver

162 阅读2分钟

在掘金社区发布文章,并在正文的第一句加入“我正在参加「掘金·启航计划」”

先上例子

// 创建观察者
let observer = new MutationObserver((mutationRecord: MutationRecord) => {
    console.log(mutationRecord)
    //
});

// 设置观察对象,即dom元素
observer.observe(document.querySelector('.observer-dom'), {
  childList: true,
  attributes: true,
  subtree: true,
  characterData: true,
  // characterDataOldValue: false
});

// 当我们停止观察时,观察器可能尚未处理某些更改。在该情况下,我们使用此方法
// 获取尚未处理的变动记录列表,表中记录的是已经发生,但回调暂未处理的变动。
// 该方法也会从 MutationObserver 的通知队列中删除所有待处理的通知
// 在 disconnect方法 前调用
observer.takeRecords()

// 在不需要的时候切记要调用此方法取消监听
observer.disconnect()

// 回调函数接受的的参数类型如下
interface MutationRecord {
    /**
     * Return the nodes added and removed respectively.
     */
    readonly addedNodes: NodeList;
    /**
     * Returns the local name of the changed attribute, and null otherwise.
     */
    readonly attributeName: string | null;
    /**
     * Returns the namespace of the changed attribute, and null otherwise.
     */
    readonly attributeNamespace: string | null;
    /**
     * Return the previous and next sibling respectively of the added or removed nodes, and null otherwise.
     */
    readonly nextSibling: Node | null;
    /**
     * The return value depends on type. For "attributes", it is the value of the changed attribute before the change. For "characterData", it is the data of the changed node before the change. For "childList", it is null.
     */
    readonly oldValue: string | null;
    /**
     * Return the previous and next sibling respectively of the added or removed nodes, and null otherwise.
     */
    readonly previousSibling: Node | null;
    /**
     * Return the nodes added and removed respectively.
     */
    readonly removedNodes: NodeList;
    /**
     * Returns the node the mutation affected, depending on the type. For "attributes", it is the element whose attribute changed. For "characterData", it is the CharacterData node. For "childList", it is the node whose children changed.
     */
    readonly target: Node;
    /**
     * Returns "attributes" if it was an attribute mutation. "characterData" if it was a mutation to a CharacterData node. And "childList" if it was a mutation to the tree of nodes.
     */
    readonly type: MutationRecordType;
}

MutationObserver是dom变化观察器,可以监听到dom节点的增删,dom属性的变化,dom文本内容的改变,并触发回调方法。

唯一需要注意的是,如果想要监听文本的变化,需要subtree属性设为true,否则修改文本不会触发回调。