给任何一个元素加上contenteditable="true"
即可使其可编辑,由此为基础即可实现一个简单的富文本编辑器了。javascript
<div contenteditable="true"></div>
当HTML文档切换到designMode
时,它的文档对象将公开一个execCommand方法来运行操做当前可编辑区域的命令,如表单输入或可知足元素。html
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
"lint": "eslint . --ext .js,.ts", "build": "webpack --env production", "start": "webpack-cli serve"
基于webpack搭建一个基础项目,yarn start
用于本地开发。yarn build
用于构建生产文件。java
import Editor from '../src/editor'; new Editor('#editor_root', { style: { height: '300px', }, });
解决range
丢失的问题webpack
当编辑器失去焦点的时候,会致使当前选中的文本丢失。因此在编辑器失去焦点的事件触发时保存当前range
git
backupRange(): void { const selection = window.getSelection(); const range = selection.getRangeAt(0); this.currentSelection = { startContainer: range.startContainer, startOffset: range.startOffset, endContainer: range.endContainer, endOffset: range.endOffset, }; }
在执行操做以前,恢复以前的rangee
es6
restoreRange(): void { if (this.currentSelection) { const selection = window.getSelection(); selection.removeAllRanges(); const range = document.createRange(); range.setStart( this.currentSelection.startContainer, this.currentSelection.startOffset, ); range.setEnd( this.currentSelection.endContainer, this.currentSelection.endOffset, ); // 向选区中添加一个区域 selection.addRange(range); } }
webpack
目前尚不支持export library 为es6 module
document.execCommand
已被标记为Obsolete源码地址github