如何在Vue&React中记住鼠标光标位置并插入文本

326 阅读1分钟

如何在Vue&React中记住鼠标光标位置并插入文本

Vue代码

<script lang="ts" setup>
// 1.定义光标位置和是否插入的flag
const blurIndexFlag = ref(false);
const blurIndex = ref(0);
const inputValue = ref('');
// 2.blur事件记住位置
const handleBlur = (e)=>{
blurIndex.value = e.srcElement.selectionStart;
blurIndexFlag.value = true;
}
// 3.自定义时机插入内容
const handleInsert = (content) => {
 if(flag){
 // 因为文本字符串无法支持索引插入,转为数组比较方便,substr比较繁琐.
  let temp=inputValue.value.split("");
  temp.splice(blurIndex.value, 0, " " + e);
  temp = temp.join("");
  inputValue.value = temp

 }else{
   // noop
 }
}
</script>
<template>
<input @blur="handleBlur"/>
</template>

React代码

// 1.定义光标位置和是否插入的flag
const [blurIndex,setBlurIndex] = useState(0);
const [blurIndexFlag,setBlurIndexFlag] = useState(false);
const [inputValue,setInputValue] = useState('');

// 2.处理插入,合成事件里少了些参数这里操作DOM
const handleInsert = (context) => {
// useRef()获取懒得改了
let textInput   = document.getElementById('myInput');
let insert      = textInput.selectionStart;
textInput.value = textInput.value.substr(0, insert) + context + textInput.value.substr(insert); 
setInputValue(textInput.value);
}
return <>
        <input id="myInput"/>
       </>