<p>MutationObserver 必须同时配置 attributes: true 与 childList: true 或 characterData: true 才能监听 class/style/data-* 等全局属性变更,且仅响应 setAttribute 等标准 attribute 操作,不响应 property 赋值;需用 attributeFilter 精准过滤并启用 attributeOldValue 获取旧值。</p>

MutationObserver 不能直接监听 HTML 全局属性(如 class、id、style、data-*)的值变更,除非你显式配置并满足四个硬性条件:目标节点必须是 Element、attributes: true 必须与 childList: true 或 characterData: true 共存、属性修改必须走标准 attribute 接口(而非 property)、且 attributeFilter 和 attributeOldValue 按需启用。漏掉任一环,监听就静默失效或直接报错。
为什么只设 attributes: true 不触发回调?
浏览器会直接抛 TypeError:因为 attributes 选项在规范中被定义为“依赖型配置”,它不能单独存在。你必须同时启用至少一个其他变更类型:
-
childList: true(监听子节点增删)——最常用,尤其当你也在意结构变化时 -
characterData: true(监听文本内容)——适用于contenteditable场景
只写 { attributes: true } 不会报错但也不工作;只写 { attributes: true, childList: false } 仍会报错——childList 必须显式为 true 才算“启用”。
class、style、data-* 修改后没反应?检查改法是否合法
这些属性只有通过 attribute 接口修改才会被监听到。以下操作**不会触发**:
立即学习“前端免费学习笔记(深入)”;
-
el.className = 'active'(改的是 DOM property) -
el.style.color = 'red'(改的是CSSStyleDeclaration对象) -
el.dataset.userId = '123'(虽然最终映射为data-user-id,但部分旧版浏览器不保证触发)
以下操作**会触发**:
el.setAttribute('class', 'active')el.setAttribute('style', 'color:red;')-
el.setAttribute('data-user-id', '123')(注意:下划线不合法,必须用连字符) -
el.classList.add('loading')(本质调用setAttribute)
如何精准监听特定全局属性,避免性能拖累?
不加过滤时,attributes: true 会监听所有属性变更(包括 aria-hidden、spellcheck 等高频项),导致回调频繁执行。正确做法是组合使用:
-
attributeFilter: ['class', 'data-status', 'data-loaded']—— 必须全小写、字符串数组,不支持通配符 -
attributeOldValue: true—— 不开就拿不到mutation.oldValue,比如判断data-status是否从"pending"变成"done"就必须依赖它 - 避免监听
style大量内联变更:如果只是关心类名切换,就别放进attributeFilter,改用class+classList更轻量
监听 data-* 时最容易忽略的三个细节
很多人以为只要写了 data- 就能被自动识别,其实有三处硬限制:
- 属性名必须符合 HTML 规范:如
data-user_id会被浏览器忽略,必须写成data-user-id -
attributeFilter中必须显式列出完整名称:'data-user-id'✅,'dataUserId'❌ - 回调中读取变更字段用
mutation.attributeName,它返回原始名('data-user-id'),不是驼峰化的dataset.userId,别拿后者去比对
真正难调试的点不在代码怎么写,而在于你监听的节点是不是真的存在、有没有被框架提前卸载、以及第一次变更是否发生在 observe() 调用之前——MutationObserver 不回溯,那一次永远丢失。



















