在contenteditable中插入自定义标记

问题描述 投票:3回答:1

我有这个:

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

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

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

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

javascript html css contenteditable
1个回答
4
投票

你需要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()作为参数。

© www.soinside.com 2019 - 2024. All rights reserved.