从本质上讲,我希望在DIV
的内容更改时执行脚本.由于脚本是分开的(Chrome扩展&;网页脚本中的内容脚本),我需要一种简单的方法来观察DOM状态的变化.我可以设置投票,但这似乎很草率.
从本质上讲,我希望在DIV
的内容更改时执行脚本.由于脚本是分开的(Chrome扩展&;网页脚本中的内容脚本),我需要一种简单的方法来观察DOM状态的变化.我可以设置投票,但这似乎很草率.
很长一段时间以来,DOM3Mutations 事件是最好的可用解决方案,但出于性能原因,它们已被弃用.DOM4 Mutation Observers是不推荐使用的DOM3Mutations 事件的替代品.它们是currently implemented in modern browsers作为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
//...
});
此示例侦听document
及其整个子树上的DOM更改,它将触发对元素属性的更改以及 struct 更改.该规范草案包含有效的mutation listener properties项内容的完整列表:
childList
- 如果要观察到目标 children 的Mutations ,设置为
true
.attributes个
- 如果要观察到目标属性的Mutations ,则设置为
true
.characterData个
- 如果要观察到目标数据的Mutations ,则设置为
true
.subtree
- 如果不仅要观察到目标基因的Mutations ,而且要观察到目标基因的后代,则设置为
true
.attributeOldValue
- 如果
attributes
设置为true,并且需要记录Mutations 之前的目标属性值,则设置为true
.characterDataOldValue
- 如果
characterData
设置为TRUE,并且需要记录Mutations 之前的目标数据,则设置为true
.attributeFilter个
- 如果不需要观察所有属性Mutations ,则设置为属性本地名称列表(不带命名空间).
(此列表自2014年4月起生效;您可以查看规范中的任何更改.)