1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>JavaScript 获取/设置光标位置,兼容Input&&TextArea。</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
6 <style>
7 body { margin: 32px; font-family: Verdana, sans-serif; font-size: 13px; }
8 .title { font-size: 18px; font-weight: bolder;margin:40px 0; }
9 .input { width: 50%; font-family: Verdana, sans-serif; font-size: 13px; text-indent: 2px; }
10 </style>
11 <script>
12 //获取光标位置
13 //单行文本框
14 function getPositionForInput(ctrl){
15 var CaretPos = 0;
16 if (document.selection) { // IE Support
17 ctrl.focus();
18 var Sel = document.selection.createRange();
19 Sel.moveStart('character', -ctrl.value.length);
20 CaretPos = Sel.text.length;
21 }else if(ctrl.selectionStart || ctrl.selectionStart == '0'){// Firefox support
22 CaretPos = ctrl.selectionStart;
23 }
24 return (CaretPos);
25 }
26 //多行文本框
27 function getPositionForTextArea(ctrl) {
28 var CaretPos = 0;
29 if(document.selection) {// IE Support
30 ctrl.focus();
31 var Sel = document.selection.createRange();
32 var Sel2 = Sel.duplicate();
33 Sel2.moveToElementText(ctrl);
34 var CaretPos = -1;
35 while(Sel2.inRange(Sel)){
36 Sel2.moveStart('character');
37 CaretPos++;
38 }
39 }else if(ctrl.selectionStart || ctrl.selectionStart == '0'){// Firefox support
40 CaretPos = ctrl.selectionStart;
41 }
42 return (CaretPos);
43 }
44 //设置光标位置函数
45 function setCursorPosition(ctrl, pos){
46 if(ctrl.setSelectionRange){
47 ctrl.focus();
48 ctrl.setSelectionRange(pos,pos);
49 }
50 else if (ctrl.createTextRange) {
51 var range = ctrl.createTextRange();
52 range.collapse(true);
53 range.moveEnd('character', pos);
54 range.moveStart('character', pos);
55 range.select();
56 }
57 }
58 //test
59 function process( id,targetId ){
60 var no = document.getElementById(id).value;
61 setCursorPosition(document.getElementById(targetId),no);
62 }
63 </script>
64 </head>
65 <body>
66 <div class="title">JavaScript 获取/设置光标位置,兼容Input&&TextArea:</div>
67 <div class="title">单行文本框</div>
68 <p><input class="input" id="textbox" name="textbox" value="Hi,www.fengfly.com!!!" /></p>
69
70 <input type="button" onclick="alert( getPositionForInput( document.getElementById('textbox') ) )" value="Get Position">
71 输入位置: <input type="text" id="no1" size="1" /><input type="button" onclick="process('no1','textbox');" value="Set Position">
72
73 <div class="title">多行文本框</div>
74 <textarea id="zhangdanNum" name="zhangdanNum" style="height:66px;246px;overflow:hidden">Hi,CssRain!!!</textarea>
75 <input type="button" onclick="alert( getPositionForTextArea( document.getElementById('zhangdanNum') ) )" value="Get Position">
76 输入位置: <input type="text" id="no2" size="1" /><input type="button" onclick="process('no2','zhangdanNum');" value="Set Position">
77 </body>
78 </html>
运行代码