当前位置: 首页 > Web前端 > HTML

从零开始用ts实现一个简单的编辑器

时间:2023-04-02 16:38:15 HTML

小目标用ts从零实现一个简单的富文本编辑器初步实现“设置标题”“加粗”“设置颜色”的基本功能知识准备的contenteditable属性为任意元素添加contenteditable="true"使其可编辑,基于此可以实现一个简单的富文本编辑器。

Document.execCommand()当一个HTML文档切换到designMode时,它??的文档对象会暴露一个execCommand方法来运行对当前可编辑区域进行操作的命令,例如表单输入或可满足的元素。document.execCommand(aCommandName,aShowDefaultUI,aValueArgument)执行过程初始化项目"lint":"eslint.--ext.js,.ts","build":"webpack--envproduction","start":"webpack-cliserve》基于webpack构建基础工程,本地开发使用yarnstart。yarnbuild用于构建生产文件。确定简单富文本编辑器的调用方式importEditorfrom'../src/editor';newEditor('#editor_root',{style:{height:'300px',},});初始化编辑器结构,实现编辑编辑器菜单,解决了范围丢失的问题。当编辑器失去焦点时,当前选中的文本也会丢失。所以保存当前的rangebackupRange():void{constselection=window.getSelection();constrange=selection.getRangeAt(0);this.currentSelection={startContainer:range.startContainer,startOffset:range.startOffset,endContainer:range.endContainer,endOffset:range.endOffset,};}在执行操作之前,恢复之前的rangerestoreRange():void{if(this.currentSelection){constselection=window.getSelection();选择.removeAllRanges();constrange=document.createRange();range.setStart(this.currentSelection.startContainer,this.currentSelection.startOffset,);range.setEnd(this.currentSelection.endContainer,this.currentSelection.endOffset,);//添加一个范围到选择selection.addRange(range);}}总结简单富文本编辑器的基本功能已经实现webpack目前不支持es6模块的导出库还没有加入单元测试document.execCommand已经标记为Obsolete源地址