Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

javascript - 获取文本输入字段中的光标位置(以字符为单位)(Get cursor position (in characters) within a text Input field)

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.

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

Basically something like a jQuery plugin would be ideal, so I could simply do

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

$("#myinput").caretPosition()
  ask by MarkB29 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Easier update:

(更新更容易:)

Use field.selectionStart example in this answer .

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

Thanks to @commonSenseCode for pointing this out.

(感谢@commonSenseCode指出这一点。)


Old answer:

(旧答案:)

Found this solution.

(找到了这个解决方案。)

Not jquery based but there is no problem to integrate it to jquery:

(不是基于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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...