目录
非 VIP 用户可前往公众号“前端基地”进行免费阅读,文章链接如下:
示例代码
editor 组件是微信小程序中用于实现富文本编辑功能的组件,支持插入图片、视频、设置文字样式等操作。以下是对 editor 组件的详细介绍、属性说明以及一个简单的案例。
示例代码如下:
editor.wxml
<view class="w">
<view class="editor">
<editor
id="editor"
placeholder="{
{placeholder}}"
bindready="onEditorReady"
bindstatuschange="onStatusChange"
></editor>
<view class="toolbar" catchtouchend="format">
<i class="icon icon-pic" catchtouchend="insertImage"></i>
<i class="icon icon-h2 {
{formats.header===2?'icon_active':''}}" data-name="header" data-value="2"></i>
<i class="icon icon-h3 {
{formats.header===3?'icon_active':''}}" data-name="header" data-value="3"></i>
<i class="icon icon-b {
{formats.bold?'icon_active':''}}" data-name="bold"></i>
<i class="icon icon-i {
{formats.italic?'icon_active':''}}" data-name="italic"></i>
<i class="icon icon-u {
{formats.underline?'icon_active':''}}" data-name="underline"></i>
<i class="icon icon-check {
{formats.list==='check'?'icon_active':''}}" data-name="list" data-value="check"></i>
<i class="icon icon-ul {
{formats.list==='ordered'?'icon_active':''}}" data-name="list" data-value="ordered"></i>
<i class="icon icon-ol {
{formats.list==='bullet'?'icon_active':''}}" data-name="list" data-value="bullet"></i>
</view>
</view>
<button bindtap="getContent" type="primary" class="btn">获取编辑器内容</button>
</view>
说明:editor 组件用于实现富文本编辑功能。placeholder 属性设置编辑器的提示信息。bindready 事件在编辑器初始化完成时触发。bindstatuschange 事件在编辑器样式变化时触发。工具栏通过 catchtouchend 事件实现样式设置功能。
editor.js
Page({
data:{
placeholder:'请输入内容',// 编辑器提示信息
formats:{}// 当前选中的样式
},
// 插入图片或视频
insertImage(){
let _this=this;
wx.chooseMedia({
count: 1,//最多选择 1 个文件
mediaType: ['image','video'],//文件类型:图片和视频
sourceType: ['album', 'camera'],// 来源:相册和相机
maxDuration: 30,// 来源:相册和相机
camera: 'back',//使用后置摄像头
success(res) {
// console.log(res.tempFiles[0].tempFilePath)
// console.log(res.tempFiles[0].size)
console.log(res);
_this.editorCtx.insertImage({
src: res.tempFiles[0].tempFilePath,// 图片路径
width:'50%',// 图片路径
success(res){
console.log(res);
}
})
}
})
},
// 图片路径
onEditorReady(){
let _this = this;
wx.createSelectorQuery().select('#editor').context(function (res) {
console.log(res)
_this.editorCtx = res.context;// 图片路径
}).exec();
},
// 设置样式
format(e){
console.log(e);
let {name,value}=e.target.dataset;
if(!name) return
this.editorCtx.format(name,value);
},
// 样式变化时触发
onStatusChange(e){
console.log(e)
this.setData({
formats:e.detail
})
},
getContent(){
if(this.editorCtx){
this.editorCtx.getContents({
success(res){
console.log('编辑器内容:',res.html);
},
fail(err){
console.error(err);
}
});
} else {
console.error('editorCtx未正确初始化');
}
}
})
说明:insertImage 方法用于从相册或相机中选择图片并插入到编辑器中。onEditorReady 方法在编辑器初始化完成后获取编辑器上下文。format 方法用于设置文本样式(如加粗、斜体等)。onStatusChange 方法监听样式变化并更新页面数据。getContent 方法用于获取编辑器的内容并打印到控制台。
属性介绍:
属性 |
描述 |
read-only |
设置编辑器为只读(默认值:false)。 |
placeholder |
提示信息。 |
show-img-size |
点击图片时显示图片大小控件(默认值:false)。 |
show-img-toolbar |
点击图片时显示工具栏控件(默认值:false)。 |
show-img-resize |
点击图片时显示修改尺寸控件(默认值: |