这是观察元素属性的示例。
见:MutationObserver
和Mutation Events
CSS
#watch {
border: 1px solid;
}
HTML
<button id="button">Click me</button>
<div id="watch" style="width: 100px; height: 50px;"></div>
Javascript
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/* global global */
(function (global) {
"use strict";
if (typeof global.MutationObserver !== "function") {
global.MutationObserver = global.WebKitMutationObserver || global.MozMutationObserver;
}
var watch = document.getElementById("watch");
function whenClicked() {
watch.style.width = "200px";
}
document.getElementById("button").addEventListener("click", whenClicked, false);
if (typeof global.MutationObserver !== "function") {
// chrome doesn't despatch an event for "DOMAttrModified"
watch.addEventListener("DOMAttrModified", function (evt) {
console.log("Attribute changed", evt.target);
}, false);
} else {
var observer = new global.MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'attributes') {
console.log("Attribute changed", mutation);
}
});
});
observer.observe(watch, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
}(window));
上jsfiddle