vue 如何获取input中光标位置,并且点击按钮在当前光标后追加内容

第一步:监听输入框的鼠标失焦事件@blur
<el-input @blur="handleInputBlur"></el-input>

第二步: 获取失去交点时的光标在输入内容中的位置,data里定义一个变量存储如 cursorIndex

handleInputBlur(e) {
  this.cursorIndex = e.srcElement.selectionStart; }

第三步:在指定光标位置添加内容,data里定义一个变量存储如 inputData,用来存储输入框中的内容

addEmoji (str) {
    console.log(str)
    if (this.maxLength - this.inputData.length >= 2) {
        let s1 = ''
        let s2 = ''
        if (this.inputData.length < this.cursorIndex) {
    
            this.inputData = this.inputData + str
        } else {
            s1 = this.inputData.substring(0, this.cursorIndex)
            s2 = this.inputData.substring(this.cursorIndex, this.inputData.length)
            this.inputData = s1 + str + s2
        }
    }
    this.emoji_show = false
    this.$refs.inputArea.focus()
}
原文地址:https://www.cnblogs.com/zhangyezi/p/15649640.html