vue el-input中点击符号,文本框中显示符号
需求
点击 + | ( )符号,页面中光标位置,展示对应的符号
点击完,光标留在原位
代码
<el-form-item prop="kwspec" label='监测关键词'>
<el-input type="textarea" placeholder="请输入监测关键词" ref="inputRef" @blur="inputBlur" v-model="ruleZyForm.kwspec" rows="6" clearable></el-input>
</el-form-item>
<el-form-item label="" prop="">
<ul class="formUl">
<li v-for="symbol, index in symbols" :key="index" @click="insertSymbol(symbol)">{{ symbol }}</li>
</ul>
</el-form-item>
data:
cursorPos: 0,
symbols: ['+', '|', '(', ')'],
methods:
inputBlur (e) {
this.cursorPos = e.srcElement.selectionStart;
},
insertSymbol (symbol) {
this.$nextTick(() => {
const input = this.$refs.inputRef.$refs.textarea;
if (input) {
const value = this.ruleZyForm.kwspec;
const leftPart = value.substring(0, this.cursorPos);
const rightPart = value.substring(this.cursorPos);
this.ruleZyForm.kwspec = `${leftPart}${symbol}${rightPart}`;
this.cursorPos += symbol.length;
input.value = this.ruleZyForm.kwspec
input.focus();
input.setSelectionRange(this.cursorPos, this.cursorPos);
}
});
},