在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来获取。