MutationRecord: attributeName 属性
只读属性 MutationRecord
的 attributeName
包含由 MutationObserver
观察到的节点的已更改属性的名称。
值
示例
获取上次更新的属性名称
在以下示例中,有四个按钮:两个更改 h1
元素的 style
属性,两个更改 h1
元素的 class
属性。该脚本使用 MutationObserver
检测更改,并将更新下面的文本以显示最后更改的属性的名称。
HTML
html
<h1 class="blue" style="color:black;" id="hiMom">Hi, Mom!</h1>
<button id="redButton">Set class to "red"</button>
<button id="blueButton">Set class to "blue"</button>
<button id="whiteButton">Set style to "color:white;"</button>
<button id="blackButton">Set style to "color:black;"</button>
<p id="log">Updated attribute name:</p>
CSS
css
.red {
background-color: red;
}
.blue {
background-color: blue;
}
JavaScript
js
const hiMom = document.querySelector("#hiMom");
const redButton = document.querySelector("#redButton");
const blueButton = document.querySelector("#blueButton ");
const whiteButton = document.querySelector("#whiteButton");
const blackButton = document.querySelector("#blackButton");
const log = document.querySelector("#log");
redButton.addEventListener("click", () => {
hiMom.classList.add("red");
hiMom.classList.remove("blue");
});
blueButton.addEventListener("click", () => {
hiMom.classList.add("blue");
hiMom.classList.remove("red");
});
whiteButton.addEventListener("click", () => {
hiMom.style.color = "white";
});
blackButton.addEventListener("click", () => {
hiMom.style.color = "black";
});
function logLastAttr(mutationRecordArray) {
for (const record of mutationRecordArray) {
if (record.type === "attributes") {
log.textContent = `Updated attribute name: ${record.attributeName}`;
}
}
}
const observer = new MutationObserver(logLastAttr);
observer.observe(hiMom, { attributes: true });
结果
规范
规范 |
---|
DOM 标准 # ref-for-dom-mutationrecord-attributename② |
浏览器兼容性
BCD 表格仅在启用 JavaScript 的浏览器中加载。