VUE 输入框实现光标插入,设置光标位置并删除光标内容
参考https://blog.csdn.net/m0_62333895/article/details/127648295
自己写的例子
const cursorPosition = ref(""); const handleFocus = (event: any) => { cursorPosition.value = event.srcElement.selectionStart; console.log("cursorPosition.value", cursorPosition.value); // const input = event.target; // if (this.text !== "") { // this.$nextTick(() => { // input.setSelectionRange(0, 1); // 设置光标位置为第一个字符之前 // }); // } else { // input.select(); // 选中全部文本 // } }; const clickToContent = (index: any, val: any) => { if (cursorPosition.value >= 0) { let num = cursorPosition.value; let cont = messageInfo.value[index].content; let right = cont.slice(0, num); let left = cont.slice(num); messageInfo.value[index].content = right + val + left; val; } console.log(index, val); }; const del = (e: any, index: any, variableDescription: any) => { console.log("del", e); console.log("variableDescription", variableDescription); let cont = messageInfo.value[index].content; if (!cont) return; let start = e.target.selectionStart; let end = e.target.selectionEnd; let variableData = JSON.parse(variableDescription); let variableList = []; console.log("variableData", variableData); for (let val in variableData) { variableList.push(variableData[val]); } variableList; if (start == end) { //删除操作判断, let left = cont.slice(end - 7, end); let right = cont.slice(end - 1, end + 5); console.log("left", left); if (variableList.includes(left)) { //判断变量中是否存在,存在则设置光标位置,不存在则不用管 e.target.setSelectionRange(end - 7, end); //设置光标位置 e.preventDefault(); //阻止浏览器的默认行为,防止删除 } else if (variableList.includes(right)) { e.target.setSelectionRange(end - 1, end + 5); e.preventDefault(); } } };