如何在Vue&React中记住鼠标光标位置并插入文本
Vue代码
<script lang="ts" setup>
const blurIndexFlag = ref(false);
const blurIndex = ref(0);
const inputValue = ref('');
const handleBlur = (e)=>{
blurIndex.value = e.srcElement.selectionStart;
blurIndexFlag.value = true;
}
const handleInsert = (content) => {
if(flag){
let temp=inputValue.value.split("");
temp.splice(blurIndex.value, 0, " " + e);
temp = temp.join("");
inputValue.value = temp
}else{
}
}
</script>
<template>
<input @blur="handleBlur"/>
</template>
React代码
const [blurIndex,setBlurIndex] = useState(0);
const [blurIndexFlag,setBlurIndexFlag] = useState(false);
const [inputValue,setInputValue] = useState('');
const handleInsert = (context) => {
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"/>
</>