为了让您快速开始使用Mutation Observer
,这里有一个小的可重用函数
/**
* Mutation Observer Helper function
* //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
* @param {string} sel The DOM selector to watch
* @param {object} opt MutationObserver options
* @param {function} cb Pass Mutation object to a callback function
*/
const Observe = (sel, opt, cb) => {
const Obs = new MutationObserver((m) => [...m].forEach(cb));
document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};
要仅跟踪某些元素的属性"style"
更改,请使用 like:class="item"
Observe(".item", {
attributesList: ["style"], // Only the "style" attribute
attributeOldValue: true, // Report also the oldValue
}, (m) => {
console.log(m); // Mutation object
});
要监视所有属性更改,而不是attributesList
使用 Array :
attributes: true
如果需要,这里有一个例子:
/**
* Mutation Observer Helper function
* //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
* @param {string} sel The DOM selector to watch
* @param {object} opt MutationObserver options
* @param {function} cb Pass Mutation object to a callback function
*/
const Observe = (sel, opt, cb) => {
const Obs = new MutationObserver((m) => [...m].forEach(cb));
document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};
// DEMO TIME:
Observe("#test", {
attributesList: ["style"],
attributeOldValue: true,
}, (m) => {
console.log(`
Old value: ${m.oldValue}
New value: ${m.target.getAttribute(m.attributeName)}
`);
});
const EL_test = document.querySelector("#test");
EL_test.addEventListener("input", () => EL_test.style.cssText = EL_test.value);
EL_test.style.cssText = EL_test.value;
* {margin:0;}
textarea {width: 60%;height: 50px;}
<textarea id="test">
background: #0bf;
color: #000;
</textarea>