从这一节开始,我们将亲自动手,使用我们之前介绍过的浏览器原生API来实现一个简单的可以处理文本的富文本编辑器。
这一个简单版的编辑器,由于我们是基于原生的API,基于浏览器原生API的能力,我们将实现以下功能:
文字输入
文字格式调整
段落格式调整
其它
通常,当用户使用富文本编辑器时,都希望点击一个按钮来实现某种功能,而传统的按钮太过丑陋,所以我们为其准备一个按钮图标。
这里,我们使用iconfont.cn 上提供的免费图标。
我们可以进入iconfont 官网,登陆后,新建一个项目:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ktRo8kIW-1670512094428)(https://gitee.com/hjb2722404/tuchuang/raw/master/img/202203101510248.png)]
然后根据功能设计,将免费图标先添加到购物车,再导入到项目中:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VKddQ9G2-1670512094431)(https://gitee.com/hjb2722404/tuchuang/raw/master/img/202203101518863.png)]
├── index.html└── static├── css│ ├── iconfont│ │ ├── demo.css│ │ ├── demo_index.html│ │ ├── iconfont.css│ │ ├── iconfont.js│ │ ├── iconfont.json│ │ ├── iconfont.svg│ │ ├── iconfont.ttf│ │ ├── iconfont.woff│ │ └── iconfont.woff2│ └── index.css└── js|——index.js
Document
注意:
我们这里为每一个按钮所在
li元素添加了command属性,这个属性就是当点击该按钮时需要传递给
document.execCommand(command);命令的命令名称参数。
.editor-box {width: 960px;margin: auto;
}.editor {width: 100%;margin-top: 50px;height: 600px;border: 1px solid #ccc;
}.editor-toolbar {width: 100%;border-bottom: 1px dotted #555;
}.editor-toolbar ul {list-style: none;
}.editor-toolbar ul li {width: 20px;height: 20px;line-height: 20px;display: inline-block;cursor: pointer;margin-left: 10px;
}
.editor-toolbar ul li .iconfont {font-size: 16px;
}
.editor-content {margin-top: 20px;height: 500px;overflow: auto;padding: 0 25px;
}

好了,我们写好了界面,下一节,我们将实现编辑器功能。
本系列文章代码可从gitee获取
(本节内容对应代码可在1.0.1 分支找到)