テキスト入力フィールド内のカーソル位置(文字数)を取得する 質問する

テキスト入力フィールド内のカーソル位置(文字数)を取得する 質問する

入力フィールド内からキャレットの位置を取得するにはどうすればよいですか?

Google でいくつかの情報を見つけましたが、確実なものはありませんでした。

基本的にはjQueryプラグインのようなものが理想的です。

$("#myinput").caretPosition()

ベストアンサー1

アップデートが簡単になりました:

使用field.selectionStart この回答の例

これを指摘してくれた@commonSenseCodeに感謝します。


古い回答:

この解決策を見つけました。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;
}

おすすめ記事