텍스트 입력 필드 내에서 커서 위치 (문자 단위) 가져 오기 가지 비트와

입력 필드 내에서 캐럿 위치를 얻으려면 어떻게해야합니까?

Google을 통해 몇 가지 비트와 조각을 찾았지만 총알은 없습니다.

기본적으로 jQuery 플러그인과 같은 것이 이상적이므로 간단히 할 수 있습니다.

$("#myinput").caretPosition()



답변

더 쉬운 업데이트 :

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


답변

맥스 덕분입니다

누군가가 그것을 사용하고 싶다면 그의 답변에있는 기능을 jQuery에 래핑했습니다.

(function($) {
    $.fn.getCursorPosition = function() {
        var input = this.get(0);
        if (!input) return; // No (input) element found
        if ('selectionStart' in input) {
            // Standard-compliant browsers
            return input.selectionStart;
        } else if (document.selection) {
            // IE
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            return sel.text.length - selLen;
        }
    }
})(jQuery);


답변

아주 쉽게

업데이트 된 답변

사용 selectionStart, 그것은이다 모든 주요 브라우저와 호환 .

document.getElementById('foobar').addEventListener('keyup', e => {
  console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />

업데이트 : 이것은 유형이 정의되지 않았거나 type="text"입력에 있을 때만 작동합니다 .


답변

매우 간단한 해결책이 있습니다. 검증 된 결과로 다음 코드 시도하십시오

<html>
<head>
<script>
    function f1(el) {
    var val = el.value;
    alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
    <button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>

나는 당신에게 fiddle_demo를 주고있다


답변

이제 이것을위한 멋진 플러그인이 있습니다 : 캐럿 플러그인

그런 다음을 사용하여 위치를 얻 $("#myTextBox").caret()거나 설정할 수 있습니다.$("#myTextBox").caret(position)


답변

   (function($) {
    $.fn.getCursorPosition = function() {
        var input = this.get(0);
        if (!input) return; // No (input) element found
        if (document.selection) {
            // IE
           input.focus();
        }
        return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
     }
   })(jQuery);


답변

여기에 몇 가지 좋은 답변이 게시되어 있지만 코드를 단순화하고 inputElement.selectionStart지원 확인을 건너 뛸 수 있다고 생각합니다 . 현재 브라우저 사용량 의 1 % 미만을 나타내는 IE8 및 이전 버전 ( 문서 참조 ) 에서만 지원되지 않습니다 .

var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;

// and if you want to know if there is a selection or not inside your input:

if (input.selectionStart != input.selectionEnd)
{
    var selectionValue =
    input.value.substring(input.selectionStart, input.selectionEnd);
}