它似乎不起作用,因为你没有改变你正在观察的任何东西。你既没有改变
- 节点的属性(
attributes: true
)document
(这是可以理解的,因为document
没有属性)
- 子节点 (
childList: true
):唯一的子节点document
是<html>
节点,您不会删除或替换它。
- 字符数据 (
characterData: true
):您没有更改任何 Text、Comment 或 ProcessingInstruction 的子项document
(也可以理解,因为document
不能有这样的子项)。
如果您更换<html>
节点,您可以看到突变观察者按配置工作。
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.target.nodeName);
});
});
observer.observe(document, {
attributes: true,
childList: true,
characterData: true
});
document.replaceChild(document.createElement('div'), document.documentElement);
您正在做的是更改元素的内容,该ol
元素是.document
如果你想听这些变化,你必须设置subtree
为 true:
observer.observe(document, {
attributes: true,
childList: true,
subtree: true,
characterData: true
});
MDN 文档中的更多信息。
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.target.nodeName);
});
});
observer.observe(document, {
attributes: true,
childList: true,
subtree: true,
characterData: true
});
<div>
<ol contenteditable oninput="">
<li>Press enter</li>
</ol>
</div>