小编典典

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

html

如何从输入字段中获得插入符的位置?

我已经通过Google找到了一些零散的信息,但是没有任何防弹证据。

基本上像jQuery插件之类的东西是理想的,所以我可以简单地做

$("#myinput").caretPosition()

阅读 383

收藏
2020-05-10

共1个答案

小编典典

找到了这个解决方案。不是基于jquery的,但是将其集成到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;
}
2020-05-10