uniapp中u-textarea获取光标位置,获取到语音识别文字后在光标位置插入文本
·
试错路程:
1.通过原生的document.getElementById获取到u-textarea标签是一个封装的组件,包含多层嵌套标签。
2.尝试通过$refs.textarea.selectionStart获取到的值每次都是-1。
3.又尝试过使用uniapp的方法uni.getSelectedTextRange确实可以获取到,但是只能在@focus里面获取,但是有个bug,获取到的索引是上一次的值,本来想解决,但是发现如果已经聚焦了没有失焦的话,再次聚焦获取不到。
成功方法:
通过document.getElementById获取到uview封装的这个元素,再通过getElementsByTagName获取到封装的textarea,再调用selectionStart方法就可以获取到
代码:
<u--textarea
id="myArea"
ref="voiceTextArea"
style="background-color: #F2F2F2"
maxlength="200"
placeholder="请输入处理意见"
v-model="auditParams.attrValue"
count
></u--textarea>
项目中是在语音识别的时候获取,此处是点击语音按钮的方法
getFocusIndex() {
// 获取textarea光标索引
let currentArea = document.getElementById('myArea').getElementsByTagName("textarea")[0];//获取当前 textarea
this.cursorIndex = currentArea.selectionStart;
// 获取光标前后的内容
this.textInfo = {
firstText: this.auditParams.attrValue.substring(0,this.cursorIndex),
lastText: this.auditParams.attrValue.substring(this.cursorIndex)
}
},
剩下的就是将字符串拼进行拼接
this.auditParams.attrValue = this.textInfo.firstText + args + this.textInfo.lastText
* 语音识别使用的是科大讯飞的插件
更多推荐



所有评论(0)