您的位置:首页 > 其它

获取光标在文本框的位置、设置光标至文本框末尾

2014-02-07 16:53 363 查看
// 获取光标在文本框的位置
function _getFocus(elem) {
var index = 0;
if (document.selection) {// IE Support
elem.focus();
var Sel = document.selection.createRange();
if (elem.nodeName === 'TEXTAREA') {//textarea
var Sel2 = Sel.duplicate();
Sel2.moveToElementText(elem);
var index = -1;
while (Sel2.inRange(Sel)) {
Sel2.moveStart('character');
index++;
};
}
else if (elem.nodeName === 'INPUT') {// input
Sel.moveStart('character', -elem.value.length);
index = Sel.text.length;
}
}
else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox support
index = elem.selectionStart;
}
return (index);
}
//光标移动至末尾
function moveEnd(obj) {
obj.focus();
var len = obj.value.length;
if (document.selection) {
var sel = obj.createTextRange();
sel.moveStart('character', len);
sel.collapse();
sel.select();
} else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
obj.selectionStart = obj.selectionEnd = len;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: