原生API编写简单富文本编辑器003

在上一节,我们实现了一个简单的富文本编辑器,但是其中很多功能按钮点击还没有反应,因为这些功能需要参数,而我们并没有提供参数,这一节就来实现这些功能,它们包括:

  • 字体
  • 字号
  • 前景色
  • 背景色
  • 插入链接
  • 取消链接

字体设置

要设置字体,首先我们需要一个字体列表,为了能够在大多数电脑上显示正确的字体,我们目前就挑选一些系统自带的常用字体组成一个字体列表。

  1. // index.js
  2. ……
  3. const fontFamilys = [
  4. '仿宋',
  5. '黑体',
  6. '楷体',
  7. '宋体',
  8. '微软雅黑',
  9. '新宋体',
  10. 'Calibri',
  11. 'Consolas',
  12. 'Droid Sans',
  13. ];

然后当我们点击字体设置按钮时,动态生成一个字体选择组件,插入到字体选择按钮下方。

  1. btn.onclick = function(e) {
  2. if (command === 'fontName') {
  3. showFontName(e);
  4. } else {
  5. document.execCommand(command, true, '');
  6. }
  7. };
  8. function showFontName(e) {
  9. // 定义字体列表
  10. const fontFamilys = [
  11. '仿宋',
  12. '黑体',
  13. '楷体',
  14. '宋体',
  15. '微软雅黑',
  16. '新宋体',
  17. 'Calibri',
  18. 'Consolas',
  19. 'Droid Sans',
  20. ];
  21. // 生成字体选择列表模板
  22. let tpl = '<div class="editor-dialog-fontfamily">';
  23. tpl += '<ul>';
  24. for (let i = 0; i < fontFamilys.length; i++) {
  25. tpl += `<li onclick="selectFontFamily('${fontFamilys[i]}')">${fontFamilys[i]}</li>`;
  26. }
  27. tpl+ '</ul>';
  28. tpl += '</div>';
  29. // 将字体选择列表填充到通用弹窗内
  30. let dialog = document.getElementById('editorDialog');
  31. dialog.innerHTML = tpl;
  32. // 获取按钮的相对位置坐标
  33. let target = e.target;
  34. let left = target.offsetLeft;
  35. let top = target.offsetTop;
  36. // 将弹窗放置在按钮下方位置并显示出来
  37. dialog.style.left = left + 'px';
  38. dialog.style.top = top + target.offsetHeight + 20 + 'px';
  39. dialog.style.display = 'block';
  40. }

在HTML中,我们需要一个专门放弹出框的元素:

  1. <div class="editor">
  2. <div id="editorBar" class="editor-toolbar">
  3. //...
  4. </div>
  5. <div id="editorContent" class="editor-content" contenteditable="true"></div>
  6. <div id="editorDialog"></div> <!-- 专门放置弹出框 -->
  7. </div>

在CSS中,给弹出框和字体选择列表一些简单的样式:

  1. .editor {
  2. // ...
  3. position: relative;
  4. }
  5. #editorDialog {
  6. position: absolute;
  7. display: none;
  8. border: 1px solid #e9e9e9;
  9. z-index: 100;
  10. }
  11. .editor-dialog-fontfamily ul {
  12. list-style: none;
  13. padding: 0;
  14. padding-right: 15px;
  15. }
  16. .editor-dialog-fontfamily ul li {
  17. height: 30px;
  18. line-height: 30px;
  19. padding-left: 10px;
  20. cursor: pointer;
  21. }
  22. .editor-dialog-fontfamily ul li:hover {
  23. background-color: #cecece;
  24. }

看看效果:

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图1

然后我们实现选择具体字体后的方法:

  1. function selectFontFamily(fontName) {
  2. const rs = document.execCommand('fontName', true, fontName);
  3. console.log(rs);
  4. }

我们发现,当我们点击选择某个字体后,编辑区中所选的文字字体并没有改变,并且控制台输出执行结果,发现是false

原因是,当我们点击某个字体的时候,浏览器就会取消编辑区内的选区,所以当我们执行命令时,并没有选区,所以会执行失败。

现在我们对上面的代码进行改造,将字体列表改造为一个下拉选框,当选择值变化时,设置字体

  1. let tpl = '<div class="editor-dialog-fontfamily">';
  2. tpl += '<select id="fontNameSelect" onchange="selectFontFamily()">';
  3. for (let i = 0; i < fontFamilys.length; i++) {
  4. tpl += `<option value="${fontFamilys[i]}" style="font-family: '${fontFamilys[i]}'">${fontFamilys[i]}</option>`;
  5. }
  6. tpl+ '</select>';
  7. tpl += '</div>';
  8. //...
  9. function selectFontFamily() {
  10. const target = document.getElementById('fontNameSelect');
  11. const rs = document.execCommand('fontName', true, target.value);
  12. console.log(rs);
  13. }

这时我们再看:

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图2

到此,终于完成了字体的设置功能,接下来我们先对字体设置功能进行一定的优化——与其点击某个按钮才弹出下拉框选择,不如一开始就用下拉框替代按钮

  1. window.onload= function() {
  2. const btns = document.getElementById('editorBar').getElementsByTagName('button');
  3. for (let i=0; i<btns.length; i++) {
  4. const btn = btns[i];
  5. const command = btn.getAttribute('command');
  6. if (command === 'fontName') {
  7. showFontName(btn);
  8. }
  9. btn.onclick = function(e) {
  10. document.execCommand(command, 'true', '');
  11. };
  12. }
  13. };
  14. function showFontName(btn) {
  15. let tpl = getFontNameTpl();
  16. const $li = btn.parentElement;
  17. $li.innerHTML = tpl;
  18. }
  19. function getFontNameTpl() {
  20. const fontFamilys = [
  21. '仿宋',
  22. '黑体',
  23. '楷体',
  24. '宋体',
  25. '微软雅黑',
  26. '新宋体',
  27. 'Calibri',
  28. 'Consolas',
  29. 'Droid Sans',
  30. 'Microsoft YaHei',
  31. ];
  32. let tpl = '';
  33. tpl += '<select id="fontNameSelect" onchange="selectFontFamily()">';
  34. for (let i = 0; i < fontFamilys.length; i++) {
  35. tpl += `<option value="${fontFamilys[i]}" style="font-family: '${fontFamilys[i]}'">${fontFamilys[i]}</option>`;
  36. }
  37. tpl+ '</select>';
  38. return tpl;
  39. }

还需要改一下CSS,取消按钮li的宽度限制,并给一个下边距:

  1. .editor-toolbar ul li {
  2. height: 20px;
  3. line-height: 20px;
  4. display: inline-block;
  5. cursor: pointer;
  6. margin-left: 10px;
  7. margin-bottom: 10px;
  8. }

看下最终效果:

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图3

字号

字号与字体是相同的作用机制,我们补充下代码:

  1. const command = btn.getAttribute('command');
  2. if (command === 'fontName') {
  3. showFontName(btn);
  4. }
  5. if (command === 'fontSize') {
  6. showFontSize(btn);
  7. }
  8. // ...
  9. function getFontSizeTpl() {
  10. const fontSizes = [
  11. '12',
  12. '14',
  13. '16',
  14. '18',
  15. '20',
  16. '24',
  17. '28',
  18. '36',
  19. '48',
  20. '72',
  21. ];
  22. let tpl = '';
  23. tpl += '<select id="fontSizeSelect" onchange="selectFontSize()">';
  24. for (let i = 0; i < fontSizes.length; i++) {
  25. tpl += `<option value="${fontSizes[i]}" style="font-size: '${fontSizes[i]}'">${fontSizes[i]}</option>`;
  26. }
  27. tpl+ '</select>';
  28. return tpl;
  29. }
  30. function showFontSize(btn) {
  31. let tpl = getFontSizeTpl();
  32. const $li = btn.parentElement;
  33. $li.innerHTML = tpl;
  34. }
  35. function selectFontSize() {
  36. const target = document.getElementById('fontSizeSelect');
  37. const rs = document.execCommand('fontSize', true, parseInt(target.value) + 'px');
  38. }

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图4

我们会发现,在下拉框中,我们未字体提供了若干以像素为单位的值,并且当用户选择时,我们会将这个像素值作为execCommand命令的参数,但是实际操作时,无论我们选择多少的字号,最后的字号始终是一样大的。

通过查看控制台元素面板,我们发现无论我们传入什么值,最终浏览器给文字加的控制字号的属性size 都是 7

再仔细翻看文档,我们看到对fontSize 命令的说明:

fontSize : 在插入点或者选中文字部分修改字体大小. 需要提供一个HTML字体尺寸 (1-7) 作为参数

所以当我们传入超出范围的不合法参数时,它会始终将字体设置为最大尺寸7

修改一下:

  1. const fontSizes = [
  2. '1',
  3. '2',
  4. '3',
  5. '4',
  6. '5',
  7. '6',
  8. '7',
  9. ];

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图5

这回就正常了,可是用户并不知道1-7代表的具体大小对应的是常见的文档软件(例如word)中的大小(通常以像素表示),我们需要继续改造:

  1. function getFontSizeTpl() {
  2. const fontSizes = [
  3. {
  4. key: 1,
  5. value: '12',
  6. },
  7. {
  8. key: 2,
  9. value: '13',
  10. },
  11. {
  12. key: 3,
  13. value: '16',
  14. },
  15. {
  16. key: 4,
  17. value: '18',
  18. },
  19. {
  20. key: 5,
  21. value: '24',
  22. },
  23. {
  24. key: 6,
  25. value: '32',
  26. },
  27. {
  28. key: 7,
  29. value: '48',
  30. },
  31. ];
  32. let tpl = '';
  33. tpl += '<select id="fontSizeSelect" onchange="selectFontSize()">';
  34. for (let i = 0; i < fontSizes.length; i++) {
  35. tpl += `<option value="${fontSizes[i].key}" style="font-size: '${fontSizes[i].value}px'">${fontSizes[i].value}</option>`;
  36. }
  37. tpl+ '</select>';
  38. return tpl;
  39. }

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图6

总算是正常了。

前景色

众所周知,要想随心所欲地设置富文本的颜色,必须提供一个颜色选择器,我们这里暂不考虑浏览器兼容性,直接使用HTML5中 typecolorinput 组件。

  1. function showColorPicker(btn, type) {
  2. let tpl = getColorPickerTpl();
  3. const $dialog = document.getElementById('editorDialog');
  4. $dialog.innerHTML = tpl;
  5. $dialog.style.top = (btn.offsetTop + btn.offsetHeight + 15) + 'px';
  6. $dialog.style.left = btn.offsetLeft + 'px';
  7. $dialog.style.display = 'block';
  8. const colorPicker = document.getElementById('colorPicker');
  9. colorPicker.addEventListener("input", setColor.bind(this, type), false);
  10. colorPicker.addEventListener("change", setColor.bind(this, type), false);
  11. document.addEventListener("click", function(e) {
  12. e.stopPropagation();
  13. const $i = btn.firstChild;
  14. if (e.target !== $i && e.target !==colorPicker) {
  15. $dialog.style.display = 'none';
  16. }
  17. });
  18. }
  19. function getColorPickerTpl(type) {
  20. const tpl = `
  21. <input type="color" id="colorPicker" />
  22. `;
  23. return tpl;
  24. }
  25. function setColor(type, event) {
  26. const $dialog = document.getElementById('editorDialog');
  27. document.execCommand(type, 'false', event.target.value);
  28. $dialog.style.display = 'none';
  29. }

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图7

背景色

背景色的逻辑与前景色一样,所以其逻辑可以复用,只需要传入不同参数即可:

  1. btn.onclick = function(e) {
  2. document.execCommand(command, 'true', '');
  3. if (command === 'fontColor') {
  4. showColorPicker(btn, 'foreColor');
  5. }
  6. if (command === 'backColor') {
  7. showColorPicker(btn, 'backColor');
  8. }
  9. };

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图8

但是,这里有一个问题,我们为文档对象和调色板绑定了事件监听,但却没有在任何地方进行解绑。

为了完善解绑功能,我们需要定义两个全局变量来分别存储设置富文本内容字体的监听函数和解绑监听隐藏调色板的函数。因为两个监听函数使用了bind 方法已便传参,但bind的问题是,它会产生一个新的函数,所以我们需要将这个新产生的函数缓存下来,以便在移除监听时传入与绑定时相同的函数。

  1. var hideColorPickerFun;
  2. var setColorFun;
  3. function showColorPicker(btn, type) {
  4. //...
  5. hideColorPickerFun = hideColorPicker.bind(document, colorPicker, $dialog, btn, type);
  6. setColorFun = setColor.bind(this, type, $dialog, colorPicker, btn);
  7. colorPicker.addEventListener("input", setColorFun, false);
  8. colorPicker.addEventListener("change", setColorFun, false);
  9. document.addEventListener("click", hideColorPickerFun, false);
  10. }
  11. function hideColorPicker(colorPicker, $dialog, btn, type, e) {
  12. e.stopPropagation();
  13. const $i = btn.firstChild;
  14. if (e.target !== $i && e.target !==colorPicker) {
  15. $dialog.style.display = 'none';
  16. document.removeEventListener('click', hideColorPickerFun, false);
  17. colorPicker.removeEventListener('input', setColorFun, false);
  18. colorPicker.removeEventListener('change', setColorFun, false);
  19. $dialog.innerHTML = '';
  20. }
  21. }
  22. function setColor(type, $dialog, colorPicker, btn, event) {
  23. document.execCommand(type, 'false', event.target.value);
  24. $dialog.style.display = 'none';
  25. document.removeEventListener('click', hideColorPickerFun, false);
  26. colorPicker.removeEventListener('input', setColorFun, false);
  27. colorPicker.removeEventListener('change', setColorFun, false);
  28. $dialog.innerHTML = '';
  29. }

另外,在给功能按钮绑定事件时,我们将条件判断改为分支判断,方便扩展:

  1. btn.onclick = function(e) {
  2. switch (command) {
  3. case 'fontColor':
  4. showColorPicker(btn, 'foreColor');
  5. break;
  6. case 'backColor':
  7. showColorPicker(btn, 'backColor');
  8. break;
  9. default:
  10. document.execCommand(command, 'true', '');
  11. }
  12. };

插入链接

插入链接的流程是当点击插入链接按钮的时候,弹出一个填写链接的输入框和一个确定按钮,点击确定按钮,为选中的文字增加链接。

直接上代码:

  1. switch (command) {
  2. case 'fontColor':
  3. showColorPicker(btn, 'foreColor');
  4. break;
  5. case 'backColor':
  6. showColorPicker(btn, 'backColor');
  7. break;
  8. case 'createLink':
  9. showLinkDialog(btn);
  10. break;
  11. default:
  12. document.execCommand(command, 'true', '');
  13. }
  14. function showLinkDialog(btn) {
  15. const tpl = getLinkDialogTpl();
  16. const $dialog = document.getElementById('editorDialog');
  17. $dialog.innerHTML = tpl;
  18. $dialog.style.top = (btn.offsetTop + btn.offsetHeight + 15) + 'px';
  19. $dialog.style.left = btn.offsetLeft + 'px';
  20. $dialog.style.display = 'block';
  21. const linkDialog = document.getElementById('linkDialog');
  22. linkDialog.focus();
  23. const createLinkBtn = document.getElementById('createLinkBtn');
  24. createLinkBtn.addEventListener('click', createLink, false);
  25. }
  26. function getLinkDialogTpl() {
  27. const tpl = `
  28. <input type="text" id="linkDialog" />
  29. <button id="createLinkBtn">确定</button>
  30. `;
  31. return tpl;
  32. }
  33. function createLink() {
  34. const linkDialog = document.getElementById('linkDialog');
  35. document.execCommand('createLink', 'false', linkDialog.value);
  36. const createLinkBtn = document.getElementById('createLinkBtn');
  37. createLinkBtn.removeEventListener('click', createLink, false);
  38. const $dialog = document.getElementById('editorDialog');
  39. $dialog.innerHTML = '';
  40. $dialog.style.display = 'none';
  41. }

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图9

但是这里还有一个问题,当我们的焦点转移到链接输入框时,编辑器中的选区就被取消了,需要我们重新选择文本后再点击确定按钮,才能添加成功。

这个问题的原因和解决方法我们先暂时搁置,后面再细讲。

取消链接

之前插入链接不起作用是因为我们的编辑器没有插入链接功能,无法插入链接,就无法验证取消链接功能,现在我们给编辑器加上了插入链接功能,插入链接后,选中链接,直接点击取消链接按钮,链接就能被取消了。

插入图片

插入图片的原理与插入链接一样。

直接上代码:

  1. switch (command) {
  2. case 'fontColor':
  3. showColorPicker(btn, 'foreColor');
  4. break;
  5. case 'backColor':
  6. showColorPicker(btn, 'backColor');
  7. break;
  8. case 'createLink':
  9. showLinkDialog(btn);
  10. break;
  11. case 'insertImage':
  12. showImageDialog(btn);
  13. break;
  14. default:
  15. document.execCommand(command, 'true', '');
  16. }
  17. function showImageDialog(btn) {
  18. const tpl = getImageDialogTpl();
  19. const $dialog = document.getElementById('editorDialog');
  20. $dialog.innerHTML = tpl;
  21. $dialog.style.top = (btn.offsetTop + btn.offsetHeight + 15) + 'px';
  22. $dialog.style.left = btn.offsetLeft + 'px';
  23. $dialog.style.display = 'block';
  24. const imageDialog = document.getElementById('imageDialog');
  25. imageDialog.focus();
  26. const createIamgeBtn = document.getElementById('createIamgeBtn');
  27. createIamgeBtn.addEventListener('click', createImage, false);
  28. }
  29. function getImageDialogTpl() {
  30. const tpl = `
  31. <input type="text" id="imageDialog" />
  32. <button id="createIamgeBtn">确定</button>
  33. `;
  34. return tpl;
  35. }
  36. function createImage() {
  37. const imageDialog = document.getElementById('imageDialog');
  38. document.execCommand('insertImage', 'false', imageDialog.value);
  39. const createLinkBtn = document.getElementById('createIamgeBtn');
  40. createIamgeBtn.removeEventListener('click', createImage, false);
  41. const $dialog = document.getElementById('editorDialog');
  42. $dialog.innerHTML = '';
  43. $dialog.style.display = 'none';
  44. }

富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图10
富文本编辑器开发系列11——原生API编写简单富文本编辑器003 - 图11

至此,我们已经实现了所有浏览器API提供的编辑功能。

当然,现在看代码,有很多冗余,不够优雅,而且功能上也还有很多问题,比如:

  1. 设置的字体是使用 font属性,而非CSS
  2. 设置的字号只接受1-7, 并且是以 size 属性而非 CSS控制,超出大小无法设置。
  3. color使用HTML的input时,始终有一个input框在那里,并且如果手动触发click显示调色板,则调色板的位置无法自动跟随
  4. link 只能创建或取消,无法修改,无法指定是以何种方式打开
  5. link和image填写框聚焦时编辑器选区会被取消

当然,这只是肉眼可见的一些问题,还有更多问题,我们下一讲统一再将。

本节所有代码可在分支 1.0.4 上找到。