【发布时间】:2017-11-27 21:44:34
【问题描述】:
如何创建MutationObserver 的观察实例以忽略一些由我的代码引起的 DOM 更改?
例如(使用 jQuery):
//initialize MutationObserver
var mo = new MutationObserver(mutations => console.log(mutations));
mo.observe(document.body, {attributes: true, subtree: true, characterData: true, attributeOldValue: true, characterDataOldValue: true, childList: true});
//case 1: perform a removal
$('.someDiv').remove();
//in this case an action is logged by MO
//case 2: perform a removal with a disconnected MO
mo.disconnect();
$('.someDiv').remove();
mo.observe(document.body, {...});
//in this case an action is logged again!
在这两种情况下,MO 都会记录我对 DOM 所做的所有更改。我想出的唯一方法是:
//case 3: perform a removal with a disconnected MO, turning on after a timeout
mo.disconnect();
$('.someDiv').remove();
setTimeout(() => mo.observe(document.body, {...}), 500); //pseudo
//in this case MO skips an action above
但这不是该问题的最佳解决方案,因为在超时期间用户可能在页面上引起了一些其他操作,或者 MutationObserver 的回调可能会在超时之后的某个时间被调用。
【问题讨论】:
标签: javascript dom mutation-observers interception