如何用JavaScript获取和设置textfield中光标位置(转)

用JavaScript获取和设置textfield中光标位置

原文:http://www.webdeveloper.com/forum/showthread.php?t=74982

<html>
 
<body style="font-family: tahoma; font-size: 8pt;">
  
<script language="JavaScript">
   
/*
   **  Returns the caret (cursor) position of the specified text field.
   **  Return value range is 0-oField.length.
   
*/
   
function doGetCaretPosition (oField) {
     
// Initialize
     var iCaretPos = 0;
     
// IE Support
     if (document.selection) { 
       
// Set focus on the element
       oField.focus ();
       
// To get cursor position, get empty selection range
       var oSel = document.selection.createRange ();
       
// Move selection start to 0 position
       oSel.moveStart ('character'-oField.value.length);
       
// The caret position is selection length
       iCaretPos = oSel.text.length;
     }
     
// Firefox support
     else if (oField.selectionStart || oField.selectionStart == '0')
       iCaretPos 
= oField.selectionStart;
     
// Return results
     return (iCaretPos);
   }

   
/*
   **  Sets the caret (cursor) position of the specified text field.
   **  Valid positions are 0-oField.length.
   
*/
   
function doSetCaretPosition (oField, iCaretPos) {
     
// IE Support
     if (document.selection) { 
       
// Set focus on the element
       oField.focus ();
       
// Create empty selection range
       var oSel = document.selection.createRange ();
       
// Move selection start and end to 0 position
       oSel.moveStart ('character'-oField.value.length);
       
// Move selection start and end to desired position
       oSel.moveStart ('character', iCaretPos);
       oSel.moveEnd (
'character'0);
       oSel.select ();
     }

     
// Firefox support
     else if (oField.selectionStart || oField.selectionStart == '0') {
       oField.selectionStart 
= iCaretPos;
       oField.selectionEnd 
= iCaretPos;
       oField.focus ();
     }
   }

  
</script>

  
<form name="blah">
   Text Field: 
<input type="text" name="nameEdit" value="">
   
<input type="button" value="Get Caret" onClick="document.getElementById('where').value=doGetCaretPosition (document.forms[0].elements[0]);">
<input id="where">
   
<hr size=1 noshade>
   New Position: 
<input type="text" name="newPosValue" value="">
   
<input type="button" value="Set Caret" onClick="doSetCaretPosition (document.blah.nameEdit, parseInt (document.blah.newPosValue.value));">
  
</form>
 
</body>
</html>
原文地址:https://www.cnblogs.com/andy65007/p/1718038.html