ExtJS5获取当前光标位置插入文本内容

在ExtJS5开发的时候,可能会碰上,将一些文本插入到当前光标的所在位置那里。

比如说,一个页面有多个文本域控件,无论选择了哪一个控件,都可以把一些文本内容插入到光标的位置。找到了一些代码,经过测试在ExtJS5中很好用,因为ExtJS5的资料比较少,现在分享给大家。

/**
 * 重写ExtJS的Textarea控件的方法
 */
Ext.override(Ext.form.TextArea, {
	getCursorPosition: function(a) {
		var b = {
			text: "",
			start: 0,
			end: 0
		};
		a.focus();
		if (a.setSelectionRange) b.start = a.selectionStart, b.end = a.selectionEnd, b.text = b.start != b.end ? a.value.substring(b.start, b.end) : "";
		else if (document.selection) {
			var c, d = document.selection.createRange(),
				e = document.body.createTextRange();
			e.moveToElementText(a);
			b.text = d.text;
			b.bookmark = d.getBookmark();
			for (c = 0; e.compareEndPoints("StartToStart", d) < 0 && d.moveStart("character", -1) !== 0; c++) a.value.charAt(c) == "\n" && c++;
			b.start = c;
			b.end = b.text.length + b.start
		}
		return b
	},
	setCursorPosition: function(a, b) {
		b || alert("You must get cursor position first.");
		if (a.setSelectionRange) a.focus(), a.setSelectionRange(b.start, b.end);
		else if (a.createTextRange) {
			var c = a.createTextRange();
			a.value.length === b.start && c.collapse(!1);
			c.select()
		}
	},
	insertAtCursor: function(a) {
		var b = this.getCursorPosition(this.inputEl.dom),
			c = b.start,
			d = b.end,
			e = this.getValue(),
			b = e.substring(0, c),
			d = e.substring(d, e.length);
		this.setValue(b + a + d);
		this.setCursorPosition(this.inputEl.dom, {
			text: "",
			start: c + a.length,
			end: c + a.length
		})
	}
});
在需要使用的时候,只需要创建一个文本域对象,然后调用insertAtCursor这个方法就行了。以上代码是在textarea里又添加了需要方法,可以看到底层其实也用了原生的JS的一些操作。

注意在ExtJS5中,有时获取DOM的元素,需要用inputEl来获取。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值