微信小程序提供了一个内置的富文本编辑器组件 <editor>,它可以用来实现 rich-editor 功能。以下是如何在微信小程序中使用 rich-editor 的详细步骤:
WXML 文件在你的 WXML 文件中添加 <editor> 组件:
<view class="container"> <editor id="editor" class="ql-container" placeholder="{{placeholder}}" bindready="onEditorReady" bindinput="onContentChange" ></editor> <view class="toolbar"> <button bindtap="format" data-name="bold">加粗</button> <button bindtap="format" data-name="italic">斜体</button> <button bindtap="format" data-name="underline">下划线</button> <button bindtap="insertImage">插入图片</button> </view> <button bindtap="getContent">获取内容</button> </view>JS 文件
在对应的 JS 文件中添加以下代码:
Page({ data: { placeholder: '请输入内容...', editorCtx: null, }, onEditorReady() { const that = this; wx.createSelectorQuery().select('#editor').context(function(res) { that.editorCtx = res.context; }).exec(); }, format(e) { let { name } = e.target.dataset; this.editorCtx.format(name); }, insertImage() { const that = this; wx.chooseImage({ count: 1, success: function(res) { that.editorCtx.insertImage({ src: res.tempFilePaths[0], data: { id: 'abcd', role: 'god' }, width: '80%', success: function() { console.log('insert image success'); } }); } }); }, onContentChange(e) { console.log('编辑器内容改变:', e.detail); }, getContent() { this.editorCtx.getContents({ success: (res) => { console.log(res.html); wx.showModal({ title: '编辑器内容', content: res.html, showCancel: false }); } }); } });WXSS 文件
为了美化编辑器,你可以在 WXSS 文件中添加一些样式:
.container { padding: 20rpx; } .ql-container { box-sizing: border-box; width: 100%; height: 300px; font-size: 16px; line-height: 1.5; overflow: auto; padding: 10px 10px 20px 10px; border: 1px solid #ECECEC; } .toolbar { box-sizing: border-box; padding: 0 10px; height: 50px; width: 100%; position: fixed; left: 0; right: 100%; bottom: 0; display: flex; align-items: center; justify-content: space-between; border: 1px solid #ECECEC; border-left: none; border-right: none; } .toolbar button { font-size: 14px; margin: 0 5px; padding: 0 10px; height: 30px; line-height: 30px; }
使用说明:
onEditorReady 函数在编辑器准备就绪时调用,它获取编辑器的上下文。
format 函数用于设置文本格式,如加粗、斜体等。
insertImage 函数用于插入图片。
onContentChange 函数在编辑器内容变化时触发。
getContent 函数用于获取编辑器的内容。
注意事项:
编辑器组件在某些版本的微信开发者工具中可能无法正常显示,但在真机上通常可以正常工作。
编辑器的内容是 HTML 格式的,在存储和展示时可能需要额外处理。
插入图片时,建议先将图片上传到服务器,然后插入图片的URL,而不是使用本地临时路径。
对于更复杂的编辑需求,可能需要自定义更多的格式化选项和功能。
在处理用户输入的富文本内容时,注意进行安全性检查,以防止XSS攻击等安全问题。
网友回复
如何编写一个chrome插件实现多线程高速下载大文件?
cdn版本的vue在网页中出现typeerror错误无法找到错误代码位置怎么办?
pywebview能否使用webrtc远程控制共享桌面和摄像头?
pywebview6.0如何让窗体接受拖拽文件获取真实的文件路径?
如何在linux系统中同时能安装运行apk的安卓应用?
python有没有离线验证码识别ocr库?
各家的ai图生视频及文生视频的api价格谁最便宜?
openai、gemini、qwen3-vl、Doubao-Seed-1.6在ui截图视觉定位这款哪家更强更准?
如何在linux上创建一个沙箱隔离的目录让python使用?
pywebview如何使用浏览器自带语音识别与webspeech 的api?