最近一段时间有需求需要在微信小程序中用到 editor 编辑器来获取文本,但是在 editor 中 使用 focus/tap 事件在微信开发者平台上可以获取到 getSelectionText 但是真机上测试都不能获取到 getSelectionText 的值,找了网上很多文档和问答都没有找到解决方案,研究了其他人的组件源码发现,editor 中 一般都是采用 独立开一个 Toolbars 来对 editor 进行操作的 尝试了一下 真机能获取到信息了 下面附上获取的最小 demo 解决方案
<template>
<view class="content">
<view class="text-area">
<editor id="editor" @ready="onEditorReady" placeholder="再次输入"></editor>
</view>
<view @tap="onSelectionText">
测试获取文本
</view>
</view>
</template>
<script>
export default {
data() {
return {
editorCtx: null
}
},
onLoad() {
},
methods: {
onSelectionText(e){
this.editorCtx.getSelectionText({
complete(res){
console.log(res,"获取的文本")
}
})
},
// 初始化
onEditorReady(){
let that = this
this.$nextTick(()=>{
uni.createSelectorQuery().in(this).select('#editor').context((res) => {
console.log(res.context);
that.editorCtx = res.context
}).exec()
setTimeout(()=>{
this.editorCtx.setContents({
html: ""
})
},1000)
})
},
}
}
</script>
<style>
</style>
最后建议 DCloud 对 uniapp 文档的部分使用功能完善下吧,uniapp挺多坑都这么来的