MutationRecord:oldValue 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

MutationRecord 只读属性 oldValue 包含在被观察节点更改之前其字符数据或属性值。

一个字符串,表示已更改的属性的旧值,如果

  • MutationObserver.observe()attributeOldValue 参数为 true
  • MutationObserver.observe()attributes 参数为 true 或省略
  • 并且突变 typeattributes

一个字符串,表示已更改的 CharacterData 节点的旧值,如果

  • MutationObserver.observe()characterDataOldValue 参数为 true
  • MutationObserver.observe()characterData 参数为 true 或省略
  • 并且突变 typecharacterData

否则,此属性为 null

示例

显示旧颜色值

在以下示例中,有一个按钮可以将 h1 的颜色更改为随机新颜色。使用 MutationObserver 来观察目标节点 (h1) 的属性更改;当检测到更改时,观察者会调用一个函数 logOldValue()

logOldValue() 函数会收到 mutationRecords 数组,其中包含 MutationRecord 对象。然后会显示 MutationRecord 对象的 oldValue 属性,并以旧值的颜色显示。

HTML

html
<h1 id="h1">Hi, Mom!</h1>
<button id="changeColorButton">Change color</button>
<p id="log"></p>

JavaScript

js
const h1 = document.getElementById("h1");
const changeValueButton = document.getElementById("changeColorButton");
const log = document.getElementById("log");

changeColorButton.addEventListener("click", () => {
  // Random 6 character hexadecimal number to use as the hex color value
  const newColor = Math.floor(Math.random() * 16777215).toString(16);
  h1.style.color = `#${newColor}`;
});

function logOldValue(mutationRecordArray) {
  for (const record of mutationRecordArray) {
    log.textContent = `Old value: ${record.oldValue}`;
    log.style.cssText = record.oldValue;
  }
}

const observer = new MutationObserver(logOldValue);
observer.observe(h1, {
  attributes: true,
  attributeOldValue: true,
});

结果

规范

规范
DOM
# ref-for-dom-mutationrecord-oldvalue②

浏览器兼容性