在项目开发中经常遇到input等设置光标位置到最后的问题,今天我查了一下Google,找到了在IE、Firefox、Opera等主流浏览器的获取光标位置(getCursortPosition)以及设置光标位置(setCursorPosition)的函数。
function getCursortPosition (ctrl) {//获取光标位置函数
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
PS:参数ctrl为input或者textarea对象
function setCaretPosition(ctrl, pos){//设置光标位置函数 if(ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos,pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); }
PS:
相关知识:
setSelectionRange
document.selection IE/Opera支持 Firefox/Safari/Chrome不支持
createRange() IE/Opera支持 Firefox/Safari/Chrome不支持
createTextRange() IE支持 Firefox/Safari/Chrome/Opera不支持
window.getSelection() Firefox/Safari/Chrome/Opera支持 IE不支持