如何在换行符上自定义contentEditable的插入div? [英] How to customize inserted divs of contentEditable on line breaks?

查看:689
本文介绍了如何在换行符上自定义contentEditable的插入div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 generate_uuid() 函数,该函数生成唯一的ID(最初从此处):

I have generate_uuid() function that generates unique ids (originally retrieved from 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代码变为:

When I add a new line to the text content, the html code becomes:

<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

As we notice, new div is identical to the previously existing div.

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

When I add more lines, the html code becomes:

<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

The same, new divs are identical to the previously existing div.

如何自定义新插入的 div s每次用户碰到换行符?我想使新插入的 div id 属性由 generate_uuid( )函数。这样的结果应该是:

How could I customize the newly inserted divs each time the user hits a line break? I want to make the id attribute for a newly inserted div be generated by the generate_uuid() function. Something like this should be the result:

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


推荐答案

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

You could use a MutationObserver to detect when a child is added and generate a dynamic 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>

这篇关于如何在换行符上自定义contentEditable的插入div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆