
? 为什么选择 wangEditor 作为移动端富文本编辑器
? wangEditor 移动端集成步骤
引入编辑器库
<link rel="stylesheet" href="https://unpkg.com/wangeditor@latest/dist/css/wangEditor.min.css">
<script src="https://unpkg.com/wangeditor@latest/dist/js/wangEditor.min.js">script>
创建编辑器容器
<div id="editor">div>
初始化编辑器
const editor = new wangEditor('#editor');
editor.create();
配置编辑器
editor.config.height = ; // 设置编辑器高度
editor.config.menus = [
'head',
'bold',
'italic',
'underline',
'strikeThrough',
'foreColor',
'backColor',
'link',
'list',
'justify',
'quote',
'image',
'table',
'code',
'undo',
'redo'
]; // 设置工具栏按钮
editor.config.uploadImgServer = '/upload-image'; // 设置图片上传接口
?️ wangEditor API 使用详解
获取编辑器内容
editor.txt.html()
方法可以获取编辑器中的 HTML 内容。例如:const html = editor.txt.html();
console.log(html);
设置编辑器内容
editor.txt.html(htmlContent)
方法可以设置编辑器中的内容。例如:editor.txt.html('这是一段测试内容
');
插入图片
editor.config.uploadImgHooks = {
before: function (files) {
// 上传前的处理
return files;
},
success: function (result, editor) {
// 上传成功后的处理
if (result.code === ) {
editor.insertImg(result.data.url);
}
},
fail: function (result, editor) {
// 上传失败后的处理
alert('图片上传失败');
}
};
监听编辑器事件
editor.txt.change = function (html) {
console.log('内容发生变化:', html);
};
? 移动端优化技巧
输入延迟优化
import { debounce } from 'lodash';
editor.txt.change = debounce(function (html) {
// 处理内容变化逻辑
}, );
触摸事件处理
editor.$textElem.on('touchstart', function (e) {
// 处理触摸开始事件
});
性能优化
- 压缩图片:在图片上传前,使用压缩库对图片进行压缩,减少图片体积。
- 异步加载:将编辑器的初始化和资源加载放在异步任务中,避免阻塞主线程。
- 代码优化:减少不必要的 DOM 操作,避免频繁的重绘和回流。
? 与其他编辑器的对比
与 TinyMCE 对比
与 Quill 对比
与 AiEditor 对比
? 常见问题解答
如何解决图片上传失败的问题?
如何自定义编辑器的样式?
如何实现多语言支持?
editor.config.lang
属性来切换语言。例如:editor.config.lang = 'zh-CN'; // 设置为中文