Javascript实现获取及设置光标位置的方法
本文实例讲述了Javascript实现获取及设置光标位置的方法。分享给大家供大家参考。具体如下:
在项目开发中经常遇到input等设置光标位置到最后的问题,今天我查了一下Google,找到了在IE、Firefox、Opera等主流浏览器的获取光标位置(getCursortPosition)以及设置光标位置(setCursorPosition)的函数。
1.获取光标位置函数:
functiongetCursortPosition(ctrl){
varCaretPos=0;//IESupport
if(document.selection){
ctrl.focus();
varSel=document.selection.createRange();
Sel.moveStart('character',-ctrl.value.length);
CaretPos=Sel.text.length;
}
//Firefoxsupport
elseif(ctrl.selectionStart||ctrl.selectionStart=='0')
CaretPos=ctrl.selectionStart;
return(CaretPos);
}
2.设置光标位置函数:
functionsetCaretPosition(ctrl,pos){
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
elseif(ctrl.createTextRange){
varrange=ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character',pos);
range.moveStart('character',pos);
range.select();
}
}
希望本文所述对大家的javascript程序设计有所帮助。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短