光标位置的获取和指定详见代码中的注释
<template> <div style="padding: 30px"> <el-form ref="formRef" :model="formData" label-width="80px" size="mini"> <el-form-item label="内容:" style="width: 600px" prop="content"> <el-input id="contentID" v-model="formData.content" type="textarea" :rows="3" ></el-input> <el-tag @click="shortEdit(item.value)" class="tagStyle" v-for="(item, index) in btnList" :key="'btn' + index" >{{ item.value }}</el-tag > </el-form-item> </el-form> </div> </template> <script> export default { data() { return { formData: {}, btnList: [ { value: "+", }, { value: "-", }, { value: "*", }, { value: "/", }, { value: "=", }, ], }; }, methods: { shortEdit(val) { let contentDom = document.getElementById("contentID"); // 获取光标选区的起始下标 let startPos = contentDom.selectionStart; // 获取光标选区的结束下标 let endPos = contentDom.selectionEnd; let oldContent = contentDom.value; // 用快捷编辑的内容替换光标选区中的内容 let newContent = oldContent.substring(0, startPos) + val + oldContent.substring(endPos); contentDom.value = newContent; // 让输入框重新获得焦点 contentDom.focus(); // 替换内容后,新的光标选区的起始下标 let newStartPos = startPos + val.length; // 设置新的光标位置(无选区时,起始下标 = 结束下标) contentDom.setSelectionRange(newStartPos, newStartPos); }, }, }; </script> <style scoped> .tagStyle { margin: 10px 10px; cursor: pointer; } </style>