【问题标题】:How to customize inserted divs of contentEditable on line breaks?如何在换行符处自定义插入的 contentEditable div?
【发布时间】:2019-03-07 20:53:13
【问题描述】:

我有 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>

相同的新divs 与先前存在的div 相同。

如何在用户每次换行时自定义新插入的divs?我想让id 新插入的div 属性由generate_uuid() 函数生成。结果应该是这样的:

<div contenteditable>
  <div id="48b62163-9f3b-4b20-8dad-dc99e27e1243">Edit text content here.<div>
  <div id="0b0e3518-1fb2-43e4-9160-6563ac0f82be">New line 1.</div>
  <div id="57d399c6-afa0-42ae-83c2-d6d7937f22d3">New line 2.</div>
  <div id="1fe51cac-bb79-47e2-bd95-e813b33e29aa">New line 3.</div>
</div>

【问题讨论】:

  • 它需要是一个 guid,还是只是一个唯一的数字?
  • @Bibberty 它必须是生成唯一编号的任何良好标准,所以我选择了 guid。因为我的应用程序预计会在不同的场景中生成许多元素,并且每个元素都应该有一个唯一的 id。
  • 滴答声会起作用。
  • 但是 jo_va 已经为你很好地解决了。

标签: javascript html contenteditable


【解决方案1】:

您可以使用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>

【讨论】:

  • 感谢 jo,很好地使用了观察者。
猜你喜欢
  • 1970-01-01
  • 2011-10-05
  • 2014-07-21
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
相关资源
最近更新 更多