我有这个:
<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()
作为参数。