[分享]js获取光标位置和设置文本框光标位置示例代码

分类:Javascript| 发布:佚名| 查看: | 发表时间:2014/1/13
长话短说,直接看下边:
代码如下:
        function getTxt1CursorPosition(){
            var oTxt1 = document.getElementById("txt1");
            var cursurPosition=-1;
            if(oTxt1.selectionStart){//非IE浏览器
                cursurPosition= oTxt1.selectionStart;
            }else{//IE
                var range = document.selection.createRange();
                range.moveStart("character",-oTxt1.value.length);
                cursurPosition=range.text.length;
            }
            alert(cursurPosition);
        }
        function setTxt1CursorPosition(i){
            var oTxt1 = document.getElementById("txt2");
            var cursurPosition=-1;
            if(oTxt1.selectionStart){//非IE浏览器
                oTxt1.selectionStart=i;
            }else{//IE
                var range = oTxt1.createTextRange();
                range.move("character",i);
                range.select();
            }
        }
        function getTa1CursorPosition(){
            var evt =window.event?window.event:getTa1CursorPosition.caller.arguments[0];
            var oTa1 = document.getElementById("ta1");
            var cursurPosition=-1;
            if(oTa1.selectionStart){//非IE浏览器
                cursurPosition= oTa1.selectionStart;
            }else{//IE
                var range = oTa1.createTextRange();
                range.moveToPoint(evt.x,evt.y);
                range.moveStart("character",-oTa1.value.length);
                cursurPosition=range.text.length;
            }
            alert(cursurPosition);
        }
        function setTa1CursorPosition(i){
            var oTa2 = document.getElementById("ta2");
            if(oTa2.selectionStart){//非IE浏览器
                oTa2.selectionStart=i;
                oTa2.selectionEnd=i;
            }else{//IE
                var range = oTa2.createTextRange();
                range.move("character",i);
                range.select();
            }
        }
365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/javascript/901.html

相关文章