问题
I need to find the current position of the cursor so I can store it in a variable. I've looked at a few SO answers and none have been successful.
What I have so far:
function getCaretPos(id) {
var el = Ext.getCmp(id);
var rng, ii=-1;
var currSelection = window.getSelection();
if(currSelection){
currSelection.modify("character", el.value.length);
// get the current position
// ii = currentPosition
}
return ii;
};
For example: I have a textfield displaying data.
MYWORD
When I place the cursor between the Y and W it should return 2. I've seen a few examples for older versions of IE but none seem to work for me in Chrome.
Does anyone know how this can be done?
回答1:
var textarea=document.getElementById('textarea');
textarea.onclick=function(){
setTimeout(function(){
console.log(textarea.selectionStart);
},1);
}
<input id="textarea" type="text" value="MYWORD">
回答2:
I have tried this code in an old version of extjs (2+) on a textfield and it works for me (just tested on IE)
It's about capture the position from the DOM.
var position = item.el.dom.selectionStart;
In your example it will be like:
function getCaretPos(id) {
var element = Ext.getCmp(id);
var currSelection = element.el.dom.selectionStart;
}
If you want to change the position you just need to set de selectionEnd value to the position you want.
element.el.dom.selectionEnd = position;
来源:https://stackoverflow.com/questions/41141212/extjs-5-get-the-current-cursor-position-in-a-textfield-or-lookupfield