gpt4 book ai didi

javascript - 在 contenteditable 中插入自定义标签

转载 作者:搜寻专家 更新时间:2023-10-31 23:18:41 27 4
gpt4 key购买 nike

我有这个:

<input type="button" value="B" onclick="document.execCommand('bold', false, '');" />
<div contenteditable="true">Lorem Ipsum...</div>

document.execCommand工作正常。但是如果想添加一个自定义标签怎么办,比如 <customtag></customtag>围绕所选文本?

按钮需要将标签添加到选定的文本中,或者如果已经有标签则将其删除。

是否有针对此的纯 HTML 解决方案。如果没有,是否有任何纯 Javascript 解决方案?

最佳答案

您需要insertHTML 命令:

基本用法:

<input type="button" value="html" onclick="document.execCommand('insertHTML', false, '<customtag>'+window.getSelection()+'</customtag>');" />

要打开和关闭自定义标签,需要更复杂的逻辑:

<input type="button" value="html" onclick="document.execCommand('insertHTML', false, toggle(window.getSelection());" />

function toggle(txt)
{
return is_enclosed_within_a_customtag(txt)
? strip_custom_tag_off(txt)
: "<customtag>"+txt+"</customtag>"
;
}

更新

函数 is_enclosed_within_a_customtag 至少可以这样实现:

function is_enclosed_within_a_customtag(txt)
{
return txt.startsWith("<customtag>") && txt.endsWith("</customtag>");
}

... 并通过 window.getSelection().toString() 作为参数被调用。

关于javascript - 在 contenteditable 中插入自定义标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48392401/

27 4 0