<template>
  <div>
    <el-input ref="input" v-model="inputValue" @focus="handleSelectionChange" id="textarea" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    }
  },
  methods: {
     
    getCaretPosition(input) {
      // 检查浏览器是否支持 selectionRange 属性
      if (typeof input.selectionStart === "number") {
        return input.selectionStart;
      } else if (document.selection) {
        // 这段代码适用于旧版本的 Internet Explorer
        input.focus();
        var selection = document.selection.createRange();
        var selectionLength = document.selection.createRange().text.length;
        selection.moveStart("character", -input.value.length);
        return selection.text.length - selectionLength;
      }
      return 0;
    },

    handleSelectionChange() {
    this.isDisabled = false;
      setTimeout(() => {
        let titleInput = document.getElementById("titleInput");
        this.staIndex = this.getCaretPosition(titleInput);
        console.log("inputFocus", this.staIndex);
      }, 0);
    },
  },
  mounted() {
    // 监听 selectionchange 事件,在光标位置发生变化时触发
    document.addEventListener('selectionchange', this.handleSelectionChange)
  },
  beforeUnmount() {
    // 组件销毁前移除事件监听器
    document.removeEventListener('selectionchange', this.handleSelectionChange)
  }
}
</script>

或者使用DOM获取元素

let textarea= document.getElementById("textarea");

let staIndex = this.getCaretPosition(textarea);

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐