vue2监测光标位置并手动定位到某个位置

vue2中开发评论模块时,在评论文本输入完成后,往往需要在文本某处插入表情或其他内容,但在打开表情列表选了表情之后,textarea失去焦点后往往无法在刚才鼠标定位处插入表情,因此需要解决以下两个需求:

1、选好表情后,执行插入动作时,需要定位好刚才光标移动到或鼠标 focus 点到的位置。

2、textarea 必须在重新聚焦时自动聚焦到定位好的位置。

这里需要对 textarea 进行监测,要对键盘移动光标和鼠标点击两个动作进行光标位置监测。

1、用 @input="getCursorPos" @focus="getCursorPos" 监测移动光标

2、用 @mousedown="getCursorPos" @mouseup="getCursorPos" 监测鼠标点击

在插入表情之前,监测光标位置后,还需要判定光标的位置,通过 textarea 获取 selectionStart 和 selectionEnd 的值得到光标的起始、结束位置,再通过调用 setSelectionRange 方法将光标的位置标注出来,实现定位。

复制代码
// 添加 emoji
addEmoji (code) {
  const obj = this.$refs.commentInput;

  // 在光标位置插入 emoji
  const startPos = obj.selectionStart; // 光标起始位置
  const endPos = obj.selectionEnd; // 光标结束位置

  // 截取内容并插入 emoji
  this.commentText = this.commentText ? this.commentText.substring(0, startPos) + code + this.commentText.substring(endPos, this.commentText.length) : code;

  obj.focus(); // 自动聚焦

  // setSelectionRange 必须在 nextTick 中才有效
  this.$nextTick(() => {
    obj.setSelectionRange(endPos, endPos);

    // 将光标位置手动定位到刚刚添加 emoji 的后面
    this.cursorPos += 2;
    obj.setSelectionRange(this.cursorPos, this.cursorPos);
  })
},

最后在定位之后,将光标向插入表情的后一位移动,以实现连续插入的效果。

下面实现光标位置的监测

复制代码
// 监测光标位置
getCursorPos () {
  // 检测光标的位置
  let commentInput = this.$refs.commentInput;

  if (commentInput) {
    this.cursorPos = commentInput.selectionStart;
  }
},

注意,这里使用的是 selectionStart,只能实现选择文本时对光标的监测,但我们可以将选择文本的起始和结束位置设置在同一个定位数值上,则相当于使用了选择文本功能,但却什么都没选,间接实现了定位到具体某个位置的功能。

相关推荐
糕冷小美n3 小时前
elementuivue2表格不覆盖整个表格添加固定属性
前端·javascript·elementui
小哥不太逍遥3 小时前
Technical Report 2024
java·服务器·前端
沐墨染3 小时前
黑词分析与可疑对话挖掘组件的设计与实现
前端·elementui·数据挖掘·数据分析·vue·visual studio code
anOnion3 小时前
构建无障碍组件之Disclosure Pattern
前端·html·交互设计
threerocks3 小时前
前端将死,Agent 永生
前端·人工智能·ai编程
问道飞鱼4 小时前
【前端知识】Vite用法从入门到实战
前端·vite·项目构建
爱上妖精的尾巴4 小时前
8-10 WPS JSA 正则表达式:贪婪匹配
服务器·前端·javascript·正则表达式·wps·jsa
shadow fish5 小时前
react学习记录(三)
javascript·学习·react.js
小疙瘩5 小时前
element-ui 中 el-upload 多文件一次性上传的实现
javascript·vue.js·ui
Aliex_git5 小时前
浏览器 API 兼容性解决方案
前端·笔记·学习