MutationObserver实例中mutation.type突变类型为attributes时有哪些属性、方法?

2025-09-21 17:14:25 30 分享链接 开发笔记 MutationObserver

MutationObserver 中,当 mutation.type === 'attributes' 时,表示监测到了元素属性的变化。与 childList 类型不同(涉及多个节点的添加/移除),attributes 类型的突变只针对单个节点的属性变化,因此获取节点的方式和包含的信息有所不同。

1. 如何获取属性变化的节点?

对于 attributes 类型的突变,直接通过 mutation.target 即可获取发生属性变化的节点。
因为属性变化是单个元素的行为,每次属性突变只会关联一个节点,不存在“多个节点”的情况(与 childListaddedNodes/removedNodes 不同)。

示例代码:

const observer = new MutationObserver((mutationsList) => {
  for (const mutation of mutationsList) {
    if (mutation.type === 'attributes') {
      // 获取属性发生变化的节点
      const changedNode = mutation.target; 
      console.log('属性变化的节点:', changedNode);
      
      // 其他关键信息
      const changedAttrName = mutation.attributeName; // 变化的属性名(如 "class"、"style")
      const oldValue = mutation.oldValue; // 变化前的属性值(需配置 attributeOldValue: true 才会有值)
      
      console.log(`节点 ${changedNode.tagName} 的 ${changedAttrName} 属性发生变化,旧值:${oldValue}`);
    }
  }
});

2. attributes 类型突变的核心属性

attributes 类型的 mutation 对象包含以下关键属性(用于描述属性变化):

  • target:发生属性变化的 DOM 节点(必选,唯一节点)。
  • attributeName:发生变化的属性名称(字符串,如 "id"、"class"、"data-xxx")。
  • attributeNamespace:如果是 XML 命名空间中的属性(如 SVG 属性),则返回命名空间 URI,HTML 中通常为 null
  • oldValue:属性变化前的值(仅当观察配置中 attributeOldValue: true 时才会存在)。

3. MutationObserver 监测的突变类型(mutation.type

mutation.type 有 3 种可能的类型,分别对应不同的 DOM 变化:

  1. childList:节点的子元素发生变化(添加/移除子节点)。
  2. attributes:节点的属性发生变化(如 classidstyle 等属性值改变)。
  3. characterData:文本节点的内容发生变化(如文本节点的 nodeValue 改变)。

注意事项

  • 若要监测 attributes 类型的变化,需在观察配置中指定 attributes: true(默认不监测)。
  • 若要限制只监测特定属性(如只监测 classstyle),可通过 attributeFilter: ['class', 'style'] 配置。
  • 若需要获取属性变化前的旧值,需配置 attributeOldValue: true

示例观察配置:

observer.observe(targetNode, {
  attributes: true, // 开启属性变化监测
  attributeFilter: ['class', 'style'], // 只监测这两个属性
  attributeOldValue: true // 记录旧值
});

MutationObserver实例中mutation.type突变类型为attributes时有哪些属性、方法?