当前位置:Gxlcms > html代码 > 利用contenteditable属性与execCommand()方法制作简易富文本编辑器_html/css_WEB-ITnose

利用contenteditable属性与execCommand()方法制作简易富文本编辑器_html/css_WEB-ITnose

时间:2021-07-01 10:21:17 帮助过:114人阅读

目录 [1]contenteditable [2]execCommand() 段落格式 文本格式 编辑 图片 [3]富文本编辑器

前面的话

  HTML5新增contenteditable全局属性,通过此属性与document.execCommand()方法来制作富文本编辑器 

contenteditable属性

  作用:指定是否可以在浏览器里编辑内容

  值:true/false

  注意:设置document.designMode ='on'时,页面的任意位置都可以编辑;使用contenteditable ='true'则只对具体元素和其包含的元素起作用

  移动端:移动端ios5以及android3之后才支持该属性

  1. <div contenteditable="">我是测试文字</div>

document.execCommand()方法

  1. document.execCommand(String aCommandName, Boolean aShowDefaultUI, String aValueArgument)//aCommandName为命令名称,不可省略//aShowDefaultUI为是否展示用户界面,默认为false,可省略//aValueArgument为额外参数值,默认为null,可省略

【1】段落格式

  [1.1]居中

  1. document.execCommand('justifyCenter');

  [1.2]左对齐

  1. document.execCommand('justifyLeft');

  [1.3]右对齐

  1. document.execCommand('justifyRight');

  [1.4]添加缩进

  1. document.execCommand('indent');

  [1.5]去掉缩进

  1. document.execCommand('outdent');

【2】文本格式

  [2.1]字体类型

  1. document.execCommand('fontname',false,sFontName)

  [2.2]字体大小

  1. document.execCommand('fontsize',false,sFontSize)

  [2.3]字体颜色

  1. document.execCommand('forecolor',false,sFontColor)

  [2.4]背景色

  1. document.execCommand('backColor',false,sBackColor)

  [2.5]加粗

  1. document.execCommand('bold');

  [2.6]斜体

  1. document.execCommand('italic');

  [2.7]下划线

  1. document.execCommand('underline');

【3】编辑

  [3.1]复制

  1. document.execCommand('copy');

  [3.2]剪切

  1. document.execCommand('cut');

  [3.3]粘贴(经测试无效)

  1. document.execCommand('paste');

  [3.4]全选

  1. document.execCommand('selectAll');

  [3.5]删除

  1. document.execCommand('delete');

  [3.6]删除光标后字符

  1. document.execCommand('forwarddelete');

  [3.7]清空格式

  1. document.execCommand('removeFormat');

  [3.8]前进一步

  1. document.execCommand('redo');

  [3.9]后退一步

  1. document.execCommand('undo');

  [3.10]打印(对firefox无效)

  1. document.execCommand('print');

【4】图片

  1. document.execCommand('insertImage',false,'image.png');

简易富文本编辑器

  1. <div class="box"> <div class="con" id="con"> <button data-name="selectAll">全选</button> <button data-name="delete">删除</button> <button data-name="undo">撤销</button> <button data-name="print">打印</button> <button data-name="bold">加粗</button> <button data-name="italic">斜线</button> <button data-name="underline">下划线</button> <button data-name="fontsize" data-value="16px">大号字体</button> <button data-name="forecolor" data-value="red">红色文本</button> <button data-name="backcolor" data-value="gray">灰色背景</button> <button data-name="removeFormat">清空格式</button> </div> <div class="show" id="show" contenteditable="">我是测试文字</div></div>

  1. .box{ width: 500px;}.con{ overflow:hidden; margin-bottom: 6px;}.con button{ float: left; padding: 2px; border: 1px solid gray; margin-right: 2px; cursor: pointer;}.show{ height: 200px; border: 2px solid rgba(0,0,0,0.3);}

  

  <演示框>选中文字后,点击下列相应属性值可进行演示

人气教程排行