与富文本编辑器的交互的主要方式就是使用 document.execCommand() 方法
该方法可以对文档执行自定义命令,并且可以应用大多数格式
该方法接收三个参数:
为了保证跨浏览器的兼容性,最好保证第二个参数为 false,因为Firefox会在该参数为 true 时报错
| 命令 | 值(第三个参数) | 说明 |
| backcolor | 颜色字符串 | 设置文档的背景颜色 |
| bold | null | 将选中的文本转为粗体显示 |
| copy | null | 将选择文本复制到剪切板 |
| createlink | URL字符串 | 将选中的文本转换为一个链接,指向目标URL |
| cut | null | 将选中文本剪切到剪切板 |
| delete | null | 删除选择的文本 |
| fontname | 字体名称 | 将选中文本修改为指定字体 |
| fontsize | 1~7 | 将选中文本修改为指定大小 |
| forecolor | 颜色字符串 | 将文本修改为指定颜色 |
| fomatblock | HTML标签 | 使用指定标签包裹选中文本 |
| indent | null | 缩进文本 |
| inserthorizontalrule | null | 在光标处插入<hr>元素 |
| insertimage | 图像URL | 在光标出插入一张图片 |
| insertorderedlist | null | 在光标处插入<ol>元素 |
| insertunorderedlist | null | 在光标处插入<ul>元素 |
| insertparagraph | null | 在光标处插入<p>元素 |
| italic | null | 将选中文本转为斜体 |
| justifycenter | null | 将文本居中对齐 |
| justifyleft | null | 将文本居左对齐 |
| outdent | null | 凸排文本 |
| paste | null | 将剪切板中的文本粘贴到指定位置 |
| removeformat | null | 撤销formatblock |
| selectall | null | 选择文档中的所有文本 |
| underline | null | 为选中文本添加下划线 |
| unlink | null | 移除文本链接 |
上述命令中,与剪切板有关的命令在不同浏览器中的实现差异极大
此外虽然所有浏览器都支持这些命令,但是这些命令产生的HTML差距极大
除了这些命令之外.还有一些与这些命令相关的方法:
Javascript高级编程学习笔记(82)—— 富文本操作(2)
原文:https://www.cnblogs.com/lhyxq/p/10505953.html