js 在光标处插入内容

开发过程中,有时会遇到这种需求,在光标处插入内容,这时就需要两个操作:

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
    },
},
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值