今天接到个需求,在富文本中增加查看源码和增加表格功能,感觉这种功能手拿把掐,但是奈于平时沉迷于移动端有段时间没写pc了,看了下官方感觉一个头两个大,于是在茫茫文档中各种借鉴(抄袭)完成了功能
1.源码功能相对来说比较简单 就是自定义工具栏
options: {
theme: 'snow',
modules: {
toolbar: {
container: [
['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
['blockquote', 'code-block'], // 引用 代码块
[{
header: 1 }, {
header: 2 }], // 1、2 级标题
[{
list: 'ordered' }, {
list: 'bullet' }], // 有序、无序列表
[{
script: 'sub' }, {
script: 'super' }], // 上标/下标
[{
indent: '-1' }, {
indent: '+1' }], // 缩进
[{
direction: 'rtl' }], // 文本方向
['link', 'image', 'video'], // 链接、图片、视频
[{
align: [] }], // 添加居中按钮
[{
color: [] }], // 文字颜色按钮
['sourceEditor'],//新添加源码的工具
]
}
}
}
在handlers中添加事件
handlers: {
sourceEditor: function () {
//添加工具方法
const reg = /\<br\>/g,
container = this.container,
firstChild = container.nextElementSibling.firstChild;
if (!this.shadeBox) {
let shadeBox = this.shadeBox = document.createElement('div');
shadeBox.style.cssText = 'position:absolute; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); cursor:pointer';
container.style.position = 'relative';
shadeBox.addEventListener('click', function () {
this.style.display = 'none';
firstChild.innerHTML = firstChild.innerText.trim();
}, false);
container.appendChild(shadeBox);
let innerHTML = firstChild.innerHTML;
innerHTML = innerHTML.replace(reg, '');
firstChild.innerText = innerHTML;
} else {
let innerHTML = firstChild.innerHTML;
innerHTML = innerHTML.replace(reg, ''