[JavaScript]设置获取光标位置
摘自http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea
1 <html> 2 <head> 3 <title>Get/Set Caret in Textarea Example</title> 4 <script> 5 function doGetCaretPosition (ctrl) { 6 7 var CaretPos = 0; 8 // IE Support 9 if (document.selection) { 10 11 ctrl.focus (); 12 var Sel = document.selection.createRange (); 13 14 Sel.moveStart ('character', -ctrl.value.length); 15 16 CaretPos = Sel.text.length; 17 } 18 // Firefox support 19 else if (ctrl.selectionStart || ctrl.selectionStart == '0') 20 CaretPos = ctrl.selectionStart; 21 22 return (CaretPos); 23 24 } 25 26 27 function setCaretPosition(ctrl, pos) 28 { 29 30 if(ctrl.setSelectionRange) 31 { 32 ctrl.focus(); 33 ctrl.setSelectionRange(pos,pos); 34 } 35 else if (ctrl.createTextRange) { 36 var range = ctrl.createTextRange(); 37 range.collapse(true); 38 range.moveEnd('character', pos); 39 range.moveStart('character', pos); 40 range.select(); 41 } 42 } 43 44 function process() 45 { 46 var no = document.getElementById('no').value; 47 setCaretPosition(document.getElementById('get'),no); 48 } 49 50 </script> 51 </head> 52 <body> 53 <textarea id="get" name="get" rows="5" cols="31">Please write some integer in the textbox given below and press "Set Position" button. Press "Get Position" button to get the position of cursor.</textarea> 54 <br> 55 Enter Caret Position: <input type="text" id="no" size="1" /><input type="button" onclick="process();" value="Set Position"> 56 <BR> 57 <input type="button" onclick="alert(doGetCaretPosition(document.getElementById('get')));" 58 value="Get Position"> 59 </body> 60 </html>
浙公网安备 33010602011771号