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② |
瀏覽器相容性
載入中…