Javascript实例技巧精选(7)—设置和获取文本框与文本域的光标位置(兼容IE和Chrome,Firefox)

>>点击这里下载完整html源码<<

截图如下:

Javascript实例技巧精选(7)—设置和获取文本框与文本域的光标位置(兼容IE和Chrome,Firefox)

本实例描述了如何用Javascript来控制和获取文本框/文本域的鼠标光标位置,以下代码兼容IE和Chrome,Firefox

<script type="text/javascript">
        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();
            }
        }
    </script>
上一篇:JavaScript实例技巧精选(13)—计算在网页上的停留时间


下一篇:Java基础-IO流对象之字符类(FileWrite与FileReader)