且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取文本输入字段中的光标位置(以字符为单位)

更新时间:2022-12-30 13:01:46

更容易更新:

在此答案中使用 field.selectionStart 示例.

感谢@commonSenseCode 指出这一点.

Thanks to @commonSenseCode for pointing this out.

旧答案:

找到了这个解决方案.不是基于 jquery,但集成到 jquery 中没有问题:

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;
}