突变观察者字符数据使用情况,没有子列表

MutationObserver characterData usage without childList

本文关键字:列表 情况 用情 观察者 字符 数据 突变      更新时间:2023-09-26

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

并且characterData : true当观察到的元素中的文本 chages e.t <span> </span><span> with some text </span> 时使用。事实证明,要观察文本更改,需要添加childList : true

谁能想到在没有子列表的情况下使用字符数据的情况?它的用途是什么?

您可以直接观察文本节点。在这种情况下,您无需观察 childList。在许多情况下,它可能很有用,例如在可内容可编辑的元素中。喜欢这个:

// 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>

相关文章: