【问题标题】:MutationObserver characterData usage without childListMutationObserver characterData 使用没有 childList
【发布时间】:2015-11-04 12:29:19
【问题描述】:

直到最近,我还认为在添加/删除子节点时使用 MutationObserver 上的 childList : true 例如从<span id='mama-span'> </span><span id='mama-span'><span id='baby-span'></span></span>

characterData : true 用于观察元素内的文本将<span> </span> 更改为<span> with some text </span>It turns out that for text change to be observed 需要加childList : true

谁能想到在没有 childList 的情况下使用characterData 的情况?它是做什么用的?

【问题讨论】:

    标签: javascript jquery html dom mutation-observers


    【解决方案1】:

    您可以直接观察一个文本节点。在这种情况下,您不需要观察 childList。在许多情况下它可能很有用,例如在 contenteditable 元素中。像这样:

    // select the target node
    var target = document.querySelector('#some-id').childNodes[0];
    
    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        console.log(mutation.type);
      });    
    });
     
    // configuration of the observer:
    var config = { attributes: true, childList: false, characterData: true };
     
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    <div id='some-id' contenteditable='true'>Modify content</div>

    【讨论】:

    • 嗨,在我的测试中,我发现如果我删除所有文本,则不会再记录任何事件。为什么以及如何解决这个问题?
    • 我们需要考虑subtreeattributeOldValuecharacterDataOldValue。解决了。​​
    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2021-01-20
    • 2022-01-08
    • 2017-06-22
    相关资源
    最近更新 更多