Get cursor position (in characters) within a text Input field

后端 未结 9 1260
孤城傲影
孤城傲影 2020-11-22 01:22

How can I get the caret position from within an input field?

I have found a few bits and pieces via Google, but nothing bullet proof.

Basically something lik

9条回答
  •  星月不相逢
    2020-11-22 01:34

    Easier update:

    Use field.selectionStart example in this answer.

    Thanks to @commonSenseCode for pointing this out.


    Old answer:

    Found this solution. Not jquery based but there is no problem to integrate it to jquery:

    /*
    ** Returns the caret (cursor) position of the specified text field (oField).
    ** Return value range is 0-oField.value.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.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
    
      // Return results
      return iCaretPos;
    }
    

提交回复
热议问题