JS的 execCommand 方法实现一个简单的富文本编辑器

 

一、document.execCommand() 

从其名字上可以看出execCommand()是用来执行命令的,当一个HTML文档切换到设计模式时,document暴露 execCommand方法,该方法允许运行命令来操纵可编辑内容区域的元素。如保存文件、打开新文件、撤消、重做、剪切、复制、删除,字体大小、背景颜色等操作,有了这个方法就可以很容易的实现网页中的文本编辑器

【1】语法

let bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

【2】参数

  • aCommandName:命令名称 
  • aShowDefaultUI:交互方式, Boolean值,true的话将显示对话框,如果为false的话,则不显示对话框,一般为 false
  • aValueArgument:动态参数,例如:插入图片需要额外的参数(image 的 url),默认为null

【3】返回值

返回一个布尔值Boolen,如果是 false  则表示操作不被支持或未被启用

二、命令

【1】backColor

修改文档的背景颜色。在styleWithCss模式下,则只影响容器元素的背景颜色。这需要一个<color> 类型的字符串值作为参数传入。注意,IE浏览器用这个设置文字的背景颜色。

document.execCommand('BackColor', 'false', sColor);

【2】bold

开启或关闭选中文字或插入点的粗体字效果。IE浏览器使用 <strong>标签,而不是<b>标签。

document.execCommand('Bold', 'false', null);

【3】copy

拷贝当前选中内容到剪贴板。启用这个功能的条件因浏览器不同而不同,而且不同时期,其启用条件也不尽相同。使用之前请检查浏览器兼容表,以确定是否可用。

document.execCommand('Copy', 'false', null );

【4】createLink

将选中内容创建为一个锚链接。这个命令需要一个hrefURI字符串作为参数值传入。URI必须包含至少一个字符,例如一个空格。(浏览器会创建一个空链接)

document.execCommand('CreateLink', 'false', sLinkURL);

【5】cut

 剪贴当前选中的文字并复制到剪贴板。启用这个功能的条件因浏览器不同而不同,而且不同时期,其启用条件也不尽相同。使用之前请检查浏览器兼容表,以确定是否可用。

document.execCommand('Cut', 'false', null);

【6】ClearAuthenticationCache

清除缓存中的所有身份验证凭据。

document.execCommand('ClearAuthenticationCache', 'false', null);

【7】contentReadOnly

通过传入一个布尔类型的参数来使能文档内容的可编辑性。(IE浏览器不支持)

document.execCommand('contentReadOnly', 'false', sBoolen);

【8】decreaseFontSize

 给选中文字加上 <small> 标签,或在选中点插入该标签。(IE浏览器不支持)

document.execCommand('decreaseFontSize', 'false', null);

【9】delete

删除选中部分.

document.execCommand('delete', 'false', null);

【10】defaultParagraphSeparator

更改在可编辑文本区域中创建新段落时使用的段落分隔符。

document.execCommand('defaultParagraphSeparator', 'false', 'br');

【11】enableAbsolutePositionEditor

启用或禁用允许移动绝对定位元素的抓取器。Firefox 63 Beta/Dev Edition 默认禁用此功能(bug 1449564)。

document.execCommand('enableAbsolutePositionEditor', 'false', null);

【12】enableInlineTableEditing

启用或禁用表格行和列插入和删除控件。(IE浏览器不支持)

document.execCommand('enableInlineTableEditing', 'false', null);

【13】enableObjectResizing

启用或禁用图像和其他对象的大小可调整大小手柄。(IE浏览器不支持)

document.execCommand('enableObjectResizing', 'false', null);

【14】fontName

在插入点或者选中文字部分修改字体名称. 需要提供一个字体名称字符串 (例如:"Arial")作为参数。

document.execCommand('fontName', 'false', sFontName);

【15】fontSize

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

document.execCommand('fontSize', 'false', sFontSize);

【16】foreColor

在插入点或者选中文字部分修改字体颜色. 需要提供一个颜色值字符串作为参数。

document.execCommand('foreColor', 'false', sForeColor);

【17】formatBlock

添加一个HTML块式标签在包含当前选择的行, 如果已经存在了,更换包含该行的块元素 (在 Firefox中, BLOCKQUOTE 是一个例外 -它将包含任何包含块元素). 需要提供一个标签名称字符串作为参数。几乎所有的块样式标签都可以使用(例如. "H1", "P", "DL", "BLOCKQUOTE"). (IE浏览器仅仅支持标题标签 H1 - H6, ADDRESS, 和 PRE,使用时还必须包含标签分隔符 < >, 例如 "<H1>".)

document.execCommand('formatBlock', 'false', sTagName);

【18】forwardDelete

删除光标所在位置的字符。 和按下删除键一样。

document.execCommand('forwardDelete', 'false', null );

【19】heading

添加一个标题标签在光标处或者所选文字上。 需要提供标签名称字符串作为参数 (例如. "H1", "H6"). (IE 和 Safari不支持)

document.execCommand('heading', 'false', sTagName);

【20】hiliteColor

更改选择或插入点的背景颜色。需要一个颜色值字符串作为值参数传递。 UseCSS 必须开启此功能。(IE浏览器不支持)

document.execCommand('hiliteColor', 'false', sHiliteColor);

【21】increaseFontSize

在选择或插入点周围添加一个BIG标签。(IE浏览器不支持)

document.execCommand('increaseFontSize', 'false', null );

【23】indent

缩进选择或插入点所在的行, 在 Firefox 中, 如果选择多行,但是这些行存在不同级别的缩进, 只有缩进最少的行被缩进。

document.execCommand('indent', 'false', null );

【24】insertBrOnReturn

控制当按下Enter键时,是插入 br 标签还是把当前块元素变成两个。(IE浏览器不支持)

document.execCommand('insertBrOnReturn', 'false', null );

【25】insertHorizontalRule

在插入点插入一个水平线(删除选中的部分)

document.execCommand('insertHorizontalRule', 'false', null );

【26】insertHTML

在插入点插入一个HTML字符串(删除选中的部分)。需要一个个HTML字符串作为参数。(IE浏览器不支持)

document.execCommand('insertHTML', 'false', sTagName);

【27】insertImage

在插入点插入一张图片(删除选中的部分)。需要一个 URL 字符串作为参数。这个 URL 图片地址至少包含一个字符。空白字符也可以(IE会创建一个链接其值为null)

document.execCommand('insertImage', 'false', sURL);

【28】insertOrderedList

在插入点或者选中文字上创建一个有序列表

document.execCommand('insertOrderedList', 'false', null );

【29】insertUnorderedList

在插入点或者选中文字上创建一个无序列表。

document.execCommand('insertUnorderedList', 'false', null );

【30】insertParagraph

在选择或当前行周围插入一个段落。(IE会在插入点插入一个段落并删除选中的部分.)

document.execCommand('insertParagraph', 'false', null );

【31】insertText

在光标插入位置插入文本内容或者覆盖所选的文本内容。

document.execCommand('insertText', 'false', sText);

【32】italic

在光标插入点开启或关闭斜体字。 (Internet Explorer 使用 EM 标签,而不是 I )

document.execCommand('italic', 'false', null );

【33】justifyCenter

对光标插入位置或者所选内容进行文字居中。

document.execCommand('justifyCenter', 'false', null );

【34】justifyFull

对光标插入位置或者所选内容进行文本对齐。

document.execCommand('justifyFull', 'false', null );

【35】justifyLeft

对光标插入位置或者所选内容进行左对齐。

document.execCommand('justifyLeft', 'false', null );

【36】justifyRight

对光标插入位置或者所选内容进行右对齐。

document.execCommand('justifyRight', 'false', null );

【37】outdent

对光标插入行或者所选行内容减少缩进量。

document.execCommand('outdent', 'false', null );

【38】paste

在光标位置粘贴剪贴板的内容,如果有被选中的内容,会被替换

document.execCommand('paste', 'false', null );

【39】redo

重做被撤销的操作。

document.execCommand('redo', 'false', null );

【40】removeFormat

对所选内容去除所有格式

document.execCommand('removeFormat', 'false', null );

【41】selectAll

选中编辑区里的全部内容。

document.execCommand('selectAll', 'false', null);

【42】strikeThrough

在光标插入点开启或关闭删除线。
 

document.execCommand('strikeThrough', 'false', null);

【43】subscript

在光标插入点开启或关闭下角标。

document.execCommand('subscript', 'false', null);

【44】superscript

在光标插入点开启或关闭上角标。

document.execCommand('superscript', 'false', null);

【45】underline

在光标插入点开启或关闭下划线。

document.execCommand('underline', 'false', null);

【46】undo

撤销最近执行的命令。

document.execCommand('undo', 'false', null);

【47】unlink

去除所选的锚链接的<a>标签

document.execCommand('unlink', 'false', null);

三、简单的富文本编辑器

【1】效果

【2】代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>

<body>
  <div class="wrap">
    <div id="butGroup">
      <button id="undo" :title="撤销">撤销</button>
      <button id="redo" :title="恢复">恢复</button>
      <button id="bold" :title="加粗">加粗</button>
      <button id="italic">倾斜</button>
      <button id="underline">下划线</button>
      <button id="strikeThrough">删除线</button>
      <button id="h1">H1</button>
      <button id="h2">H2</button>
      <button id="h3">H3</button>
      <button id="foreColor">字体颜色</button>
      <button id="hiliteColor">字体背景</button>
      <button id="insertOrderedList">有序</button>
      <button id="insertUnorderedList">无序</button>
      <button id="save">提交</button>
    </div>
    <iframe id='HtmlEdit' style="width:800px; height: 400px" marginWidth='10px' marginHeight='10px'></iframe>
  </div>

  <div id="box" style="height: 400px;width: 800px;border: 1px solid black">
  </div>

  <script language="javascript">
    window.onload = function () {
      let editor = document.getElementById("HtmlEdit").contentWindow;//获取iframe Window 对象
      let doc = document.getElementById("HtmlEdit").contentDocument; //获取iframe documen 对象
      let butGroup = document.getElementById('butGroup');
      let box = document.getElementById('box');
      //设置事件监听
      butGroup.addEventListener('click', function (e) {
        //通过e 事件 获取点击的标签 id
        switch (e.target.id) {
          case 'undo': undo(); break;
          case 'redo': redo(); break;
          case 'bold': bold(); break;
          case 'copy': copy(); break;
          case 'italic': italic(); break
          case 'underline': underline(); break;
          case 'strikeThrough': strikeThrough(); break;
          case 'h1': h1(); break;
          case 'h2': h2(); break;
          case 'h3': h3(); break;
          case 'foreColor': foreColor(); break;
          case 'hiliteColor': hiliteColor(); break;
          case 'insertOrderedList': insertOrderedList(); break;
          case 'insertUnorderedList': insertUnorderedList(); break;
          case 'save': save(); break
        }
      })

      //只需键入以下设定,iframe立刻变成编辑器。
      editor.document.designMode = 'On';  //打开设计模式
      editor.document.contentEditable = true;// 设置元素为可编辑

      // 撤销
      let undo = () => { editor.document.execCommand('undo', false, null) }

      // 恢复
      let redo = () => { editor.document.execCommand('redo', false, null) }

      // 加粗
      let bold = () => { editor.document.execCommand('bold', false, null) }

      // 斜体
      let italic = () => { editor.document.execCommand('italic', false, null) }

      // 下划线
      let underline = () => { editor.document.execCommand('underline', false, null) }

      // 删除线
      let strikeThrough = () => { editor.document.execCommand('strikeThrough', false, null) }

      // H1
      let h1 = () => { editor.document.execCommand('fontSize', false, 7) }

      // H2
      let h2 = () => { editor.document.execCommand('fontSize', false, 6) }

      // H3
      let h3 = () => { editor.document.execCommand('fontSize', false, 5) }

      // 字体颜色
      let foreColor = () => { editor.document.execCommand('foreColor', false, 'red') }

      // 字体背景
      let hiliteColor = () => { editor.document.execCommand('hiliteColor', false, 'yellow') }

      // 有序列表
      let insertOrderedList = () => { editor.document.execCommand('insertOrderedList', false, null) }

      // 无序列表
      let insertUnorderedList = () => { editor.document.execCommand('insertUnorderedList', false, null) }

      // 提交
      let save = () => { box.innerHTML = doc.body.innerHTML }
    }
  </script>
</body>

</html>

文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料

 

 

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Demi

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值