为什么DOMSubtreeModified事件被废弃了,我们应该使用什么替代它?请参考此链接。
警告!
MutationEvent
接口是在DOM Level 2 Events中引入的,但尚未在所有用户代理中完全和互操作地实现。此外,有人批评该接口的设计引入了性能和实现挑战。正在制定一个新规范,旨在解决变异事件解决的用例,但以更高效的方式。因此,本规范描述了变异事件以参考和完整性的遗留行为,但不建议使用MutationEvent
接口和MutationNameEvent
接口。
替代API是变异观察器, 它们在DOM Living Standard中得到了完全的规定,这取代了所有DOM级别X的愚蠢。
我认为替代方案将是Mutation Observers:https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver
var whatToObserve = {childList: true, attributes: true, subtree: true, attributeOldValue: true, attributeFilter: ['class', 'style']};
var mutationObserver = new MutationObserver(function(mutationRecords) {
$.each(mutationRecords, function(index, mutationRecord) {
if (mutationRecord.type === 'childList') {
if (mutationRecord.addedNodes.length > 0) {
//DOM node added, do something
}
else if (mutationRecord.removedNodes.length > 0) {
//DOM node removed, do something
}
}
else if (mutationRecord.type === 'attributes') {
if (mutationRecord.attributeName === 'class') {
//class changed, do something
}
}
});
});
mutationObserver.observe(document.body, whatToObserve);
MutationEvent
接口的技巧是使用animationStart
以及一些 CSS。 - Andres RiofrioDOMSubtreeModified
允许从根节点观察整个树。 - xmo