input输入框失去焦点时获取光标位置并插入内容

 

<el-input @blur="blur" :rows="5" v-model="messageForm.content" type="textarea" maxlength="100" show-word-limit placeholder="请输入你的留言"></el-input>

 

data() {
      return {
        cursorIndexStart: null,//光标选中开始的位置
        cursorIndexEnd: null,//光标选中结束的位置
      }
    },

 

      blur(e){
        this.cursorIndexStart = e.srcElement.selectionStart  // 获取input输入框失去焦点时光标选中开始的位置
        this.cursorIndexEnd = e.srcElement.selectionEnd  // 获取input输入框失去焦点时光标选中结束的位置
      },
    //在光标处插入数据 output(val) {
if (this.cursorIndexStart !== null && this.messageForm.content) { //如果 文本域获取了焦点, 则在光标位置处插入对应字段内容 this.messageForm.content = this.messageForm.content.substring(0, this.cursorIndexStart) + val + this.messageForm.content.substring(this.cursorIndexEnd) } else { // 如果 文本域未获取焦点, 则在字符串末尾处插入对应字段内容 this.messageForm.content = this.messageForm.content?this.messageForm.content:'' + val } },

 

posted @ 2023-06-11 16:46  Ning-  阅读(196)  评论(0编辑  收藏  举报