javascript获取光标位置以及设置光标位置

来源:互联网 发布:双线性插值算法 编辑:程序博客网 时间:2024/05/17 22:27

在项目开发中经常遇到input等设置光标位置到最后的问题,今天我查了一下Google,找到了在IE、Firefox、Opera等主流浏览器的获取光标位置(getCursortPosition)以及设置光标位置(setCursorPosition)的函数。


function getCursortPosition (ctrl) {//获取光标位置函数var CaretPos = 0;// IE Supportif (document.selection) {ctrl.focus ();var Sel = document.selection.createRange ();Sel.moveStart ('character', -ctrl.value.length);CaretPos = Sel.text.length;}// Firefox supportelse 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:参数ctrl为input或者textarea对象,pos为光标要移动到的位置。



原创粉丝点击