开发过程中,有时会遇到这种需求,在光标处插入内容,这时就需要两个操作:
1、获取光标位置
2、在光标处插入内容
假如有一个文本域、一个下拉框,要求把下拉框选中的值插入到文本域中的指定位置
<el-input
id="textarea"
type="textarea"
:autosize="{ minRows: 2}"
v-model="form.content"
placeholder="请输入"
clearable
@input="input"
></el-input>
<el-select v-model="field" @change="selectField" placeholder="请选择">
<el-option
v-for="item in fieldList"
:key="item.value"
:label="item.name"
:value="item.value"
></el-option>
</el-select>
首先有几种情况:
1)未点击文本域,直接选择下拉框内容,这时,直接拼接在文本域中字符串的末尾
methods: {
selectField(value){
this.form.content += value
},
},
2)点击了文本域中字符串的任意位置,然后选择下拉框中的值,插入到文本域中字符串刚才点击的位置
mounted(){
this.cursorIndex = null // 初始化光标在文本域中的位置
document.onclick = (e) => { // 文本域获取焦点
if(e.target.tagName=="TEXTAREA"){
this.textarea_dom = e.target // 获取文本域 dom 元素
this.textareaFocus(e.target)
}
}
this.$nextTick(() => this.textarea_dom = document.getElementById('textarea'))
},
methods: {
// 文本域获取焦点
textareaFocus(dom){
let index = 0
if (document.selection) {
// 兼容IE
dom.focus()
const range = document.selection.createRange()
range.moveStart('character', -dom.value.length)
index = range.text.length
} else if (dom.selectionStart || dom.selectionStart == 0) {
index = dom.selectionStart
}
this.cursorIndex = index // 获取光标在文本域中文本的位置
},
// 下拉框 change 事件
selectField(value){
this.textarea_dom.focus()
let selectRange
if (document.selection) {
// 兼容IE
selectRange = document.selection.createRange()
selectRange.text = value
}else if (this.cursorIndex !== null && this.form.content) {
//如果 文本域获取了焦点, 则在光标位置处插入对应字段内容
const index = this.cursorIndex // 刚才光标在文本域中的位置
this.form.content = this.form.content.substring(0, index) + value + this.form.content.substring(index)
}else {
// 如果 文本域未获取焦点, 则在字符串末尾处插入对应字段内容
this.form.content += value
}
this.textarea_dom.blur() // 手动触发表单校验
},
},
3)点击了文本域中的任意位置,但是输入了先输入了部分内容,再选择下拉框的值
methods: {
// 文本域输入事件 -- 输入内容时, 重新初始化光标位置为输入内容的末尾
input(text){
this.cursorIndex = text.length
},
},