如何在换行符上自定义contentEditable的插入div?

时间:2019-03-07 20:53:13

标签: javascript html contenteditable

我有 generate_uuid() 函数,该函数生成唯一的ID(最初从here中检索):

function generate_uuid() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  )
}

我有 contentEditable div

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
</div>

当我在文本内容中添加新行时,html代码变为:

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 1.</div>
</div>

我们注意到,新的div与以前的div相同。

当我添加更多行时,html代码变为:

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 1.</div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 2.</div>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">New line 3.</div>
</div>

相同的新div与以前存在的div相同。

如何在用户每次遇到换行符时自定义新插入的div?我想通过id函数生成新插入的div的{​​{1}}属性。结果应该是这样的:

generate_uuid()

1 个答案:

答案 0 :(得分:2)

您可以使用MutationObserver来检测何时添加了孩子并生成动态ID:

function uuid() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  )
}

function subscriber(mutations) {
  mutations.forEach(mutation => {
    mutation.addedNodes.forEach(node => node.id = uuid());
    console.clear();
    console.log([...mutation.target.children].map(x => x.id));
  });
}

const observer = new MutationObserver(subscriber);
observer.observe(document.querySelector('div[contenteditable]'), { childList: true });
<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
</div>