Several years later, there is now officially a better solution.(几年后,现在正式有了更好的解决方案。)
DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events.(DOM4突变观察者代替了不推荐使用的DOM3突变事件。) They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):(目前,它们在现代浏览器中以MutationObserver
(或在旧版Chrome中作为供应商前缀的WebKitMutationObserver
)实现:)
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes.(本示例侦听document
及其整个子树上的DOM更改,并将在元素属性更改和结构更改时触发。)
The draft spec has a full list of valid mutation listener properties :(规范草案包含有效的变异侦听器属性的完整列表:)
childList(childList)
- Set to
true
if mutations to target's children are to be observed.(如果要观察到目标儿童的突变,则设置为true
。)
attributes(属性)
- Set to
true
if mutations to target's attributes are to be observed.(如果要观察到目标属性的变异,则设置为true
。)
characterData(characterData)
- Set to
true
if mutations to target's data are to be observed.(如果要观察到目标数据的变异,则设置为true
。)
subtree(子树)
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.(如果不仅要观察目标,还要观察目标的后代,则将其设置为true
。)
attributeOldValue(attributeOldValue)
- Set to
true
if attributes
is set to true and target's attribute value before the mutation needs to be recorded.(设置为true
,如果attributes
被设置为true,目标的属性值将被记录在突变前需要。)
characterDataOldValue(characterDataOldValue)
- Set to
true
if characterData
is set to true and target's data before the mutation needs to be recorded.(设置为true
,如果characterData
设置为true和目标的数据将被记录在突变前需要。)
attributeFilter(attributeFilter)
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.(如果不需要观察所有属性突变,则设置为属性本地名称(无名称空间)的列表。)
(This list is current as of April 2014; you may check the specification for any changes.)((此列表是截至2014年4月的最新信息;您可以检查规格中是否有任何更改。))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…