题外话:写到现在好像写的也不一定是vue-element-admin的坑,大家忽略标题吧。
textarea中在光标处插入字符,碰到的2个问题(其实这才是标题)
需求:在文本编辑框中的光标处插入特定字符。不管当前焦点是否在编辑框,插入后光标选中插入的字符。
实现参考这个文档:
https://blog.youkuaiyun.com/Beth__hui/article/details/96287764
把关键代码贴一下:
const areaField = this.$refs.voicearea; // 拿到目标标签;
// IE浏览器
if (document.selection) {
areaField.focus();
const sel = document.selection.createRange();
sel.text = item.text;
} // 谷歌 Firefox 等
else if (areaField.selectionStart || areaField.selectionStart === '0') {
const startPos = areaField.selectionStart;
const endPos = areaField.selectionEnd;
const restoreTop = areaField.scrollTop; // 获取滚动条高度
// this.waitingTextArea 是v-model的值
// item.text 是 选择的要插入的值
this.waitingTextArea = this.waitingTextArea.substring(0, startPos) + item.text
+ this.waitingTextArea.substring(endPos, this.waitingTextArea.length);
if (restoreTop > 0) {
areaField.scrollTop = restoreTop;
}
areaField.focus();
areaField.selectionStart = startPos + item.text.length;
areaField.selectionEnd = startPos + item.text.length;
} else {
this.waitingTextArea += item.text;
areaField.focus();
}
补充一下,在html的template中编辑框的代码:
<el-input ref="voicearea" :rows="8" v-model="waitingTextArea" type="textarea"/>
但这个代码抄过来是有问题的,areaField.focus();根本不起作用。
后来又找到这个帖子:
按上面的说法,this.$refs.voicearea里面应该还有一层,那才是真正的textarea。但是他说是 :
To access the actual <textarea>
element, you can do it by accessing the inner $refs
of your codeInput
ref since under the hood, the textarea
element has a ref called input
然后我把第一行代码改成:const areaField = this.$refs.voicearea.$refs.input; // 拿到目标标签;
还是不行。
第二行加一代码console.log(this.$refs.voicearea),用chrome在页面调试,看到里面的子节点是textarea,然后看html源代码也是textarea,于是第一行改成
const areaField = this.$refs.voicearea.$refs.textarea; // 拿到目标标签;
成功!
另外一个问题,插入后光标一直在文本最后,不能选中插入的字符串,问题在倒数5,6行这里:
为了达到需求,我改成了:
areaField.selectionStart = startPos;
areaField.selectionEnd = startPos + item.text.length;
但不管怎么设置都不起作用。然后我尝试在chrome的console中直接输入命令,是可以实现的。
猜想应该是没渲染就执行了代码,导致没生效,于是改为:
this.$nextTick( => {
areaField.selectionStart = startPos;
areaField.selectionEnd = startPos + item.text.length;
})
成功!