如何将document.execCommand(“superscript”)切换回普通文本

How to toggle off document.execCommand("superscript") back to normal text

提问人:Abiola Aribisala 提问时间:10/5/2023 更新时间:10/6/2023 访问量:27

问:

我正在使用具有基本格式功能的 contenteditable div 开发自定义文本编辑器。我正在使用该命令来执行上标功能,例如 EXAMPLETEST。我可以使用什么命令将其转回普通文本。document.execCommand("superscript", false, undefined);

Ps. 再次单击初始命令不起作用

我已经尝试过了,但两者都无法将其关闭。document.execCommand("superscript", false, undefined);document.execCommand("removeFormat", false, undefined);

javascript html 编辑器 text-editor exec命令

评论


答:

0赞 Afzal K. 10/6/2023 #1

上标是一个切换函数,它只有在文本不存在时才起作用

因此,要使文本恢复正常,我们将不得不再次使用该命令,但要确保文本存在,因此有一种方法可以使用方法检查选择中是否存在文本document.queryCommandState()

if (document.queryCommandState("superscript")) {
  document.execCommand("superscript", false, undefined);  
} else {  
  // there is no text
}  

使用 removeFormat 不是最佳选择,因为它将删除所有格式

这有帮助吗?