MutationRecord:oldValue 属性
MutationRecord 只读属性 oldValue 包含在被观察节点更改之前其字符数据或属性值。
值
一个字符串,表示已更改的属性的旧值,如果
MutationObserver.observe()的attributeOldValue参数为trueMutationObserver.observe()的attributes参数为true或省略- 并且突变
type为attributes。
一个字符串,表示已更改的 CharacterData 节点的旧值,如果
MutationObserver.observe()的characterDataOldValue参数为trueMutationObserver.observe()的characterData参数为true或省略- 并且突变
type为characterData。
否则,此属性为 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② |
浏览器兼容性
加载中…