需求背景
最近接到一个需求:在文本框中可以插入超链(方便查看某个关键词包含的详细信息),并且对该需求进行优化,最后要呈现的效果为前端检测用户输入,在用户输入某个字符时(如@)在当前输入的光标处插入筛选框(筛选项为可选择的关键词,且支持模糊筛选);因为文本域不支持插入超链接,所以最后选择使用富文本来实现(功能类似于知乎写文章时的@功能)
效果
技术调研
注:技术调研的过程主要调研了三款富文本(CKEditor、wangEditor、Quill),涉及了这几个方面:是否开源、Star(Github)、是否还在维护、文档是否齐全(important)、大小、插件数量、兼容性
使用感受
CKEditor :
文档为英文的,上手使用较慢;
对应功能的demo几乎找不到对于刚接触使用的人来说很不友好;
虽然界面挺简约好看但对于我来说用着很痛苦~.~
wangEditor:
轻量(804kb),支持ie6+;
不支持使用JS在光位置插入内容;
上手快,每个功能多数都有对应的demo代码;
插件功能较少,功能比较单一,实现额外的功能,需要自己扩展;
Quill:
轻量(300kb),上手使用较快;
插入select标签只能将option标签的文本内容渲染到编辑器中
需求实现
使用原生属性(contentEditable)实现
原因:
以上调研的富文本编辑器,在使用过程中,自定义功能使用不是很方便,实现过程耗时太长,时间成本太高(可能是没怎么用 过),并且这个需求要实现的功能所依赖的为可识别html文本的编辑器,而contentEditable全局属性即可达到目的,综上原因最后选择使用原生属性(contentEditable)实现。
需求项目所用的技术栈
Vue + Element
主要实现思路
首先给想要实现可编辑的元素添加contentEditable属性;其次监听键盘事件,当用户输入’[‘ 时在光标处插入一个空标签,并获取空标签的位置,用来作为将要插入的下拉框select位置,最后选择完要插入的链接选项后,移除多余的空标签
具体实现过程
注:最下面有该功能组件完整代码(封装后的)
组件UI层
1 | <div id="editor"></div> |
组件关键代码
1 | let editor = document.getElementById("editor") |
使用(父组件)
1 | <richTxt :insertBI='indTypeAll' :htmlStr="form.definition || ''" @txtChange="contentChange"></richTxt> |
组件完整代码
1 | <template> |