입력 필드 내에서 캐럿 위치를 얻으려면 어떻게해야합니까?
Google을 통해 몇 가지 비트와 조각을 찾았지만 총알은 없습니다.
기본적으로 jQuery 플러그인과 같은 것이 이상적이므로 간단히 할 수 있습니다.
$("#myinput").caretPosition()
<input>것이에서 수행하는 것보다 훨씬 간단합니다 <textarea>.
size문자를 지나면 더 어려워집니다 .
입력 필드 내에서 캐럿 위치를 얻으려면 어떻게해야합니까?
Google을 통해 몇 가지 비트와 조각을 찾았지만 총알은 없습니다.
기본적으로 jQuery 플러그인과 같은 것이 이상적이므로 간단히 할 수 있습니다.
$("#myinput").caretPosition()
<input>것이에서 수행하는 것보다 훨씬 간단합니다 <textarea>.
size문자를 지나면 더 어려워집니다 .
답변:
더 쉬운 업데이트 :
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;
}
else if (oField.selectionStart || oField.selectionStart == '0')일 수else if (typeof oField.selectionStart==='number')
document.selection그렇지 않은 field.selection것입니다. 또한 IE 7 (8 이상에서는 여전히 가능한지 알 수 없음)에서 무언가를 선택한 다음 선택을 잃지 않고 필드에서 Tab 키를 눌러도 가능합니다. 이 방법으로 텍스트를 선택했지만 필드에 초점이 맞지 않으면 document.selection0 선택을 반환합니다. 그렇기 때문에이 버그의 해결 방법으로를 읽기 전에 요소에 집중해야합니다 document.selection.
맥스 덕분입니다
누군가가 그것을 사용하고 싶다면 그의 답변에있는 기능을 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);
input = $(this).get(0)같은 input = this?
this에서 전체 포장 세트를 나타냅니다. 그의 코드는 여전히 잘못되어 있습니다 this.get(0). 래핑 된 세트를 다시 랩핑해도 아무런 효과가 없기 때문에 코드가 여전히 작동했을 것입니다.
사용 selectionStart, 그것은이다 모든 주요 브라우저와 호환 .
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
업데이트 : 이것은 유형이 정의되지 않았거나 type="text"입력에 있을 때만 작동합니다 .
.selectionStart언제라도 속성을 확인할 수 있습니다 ( document.getElementById('foobar').selectionStart). 이벤트 리스너 안에있을 필요는 없습니다.
매우 간단한 해결책이 있습니다. 검증 된 결과로 다음 코드 를 시도하십시오 -
<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를 주고있다
slice상대적으로 비싼 작업이며이 '솔루션'에 아무것도 추가하지 않습니다 el.selectionStart. 슬라이스의 길이와 같습니다. 그냥 돌려주십시오. 또한 다른 솔루션이 더 복잡한 이유는 지원하지 않는 다른 브라우저를 처리하기 때문 selectionStart입니다.
f1'user2782001'만큼 의미가 있습니다. 😉
이제 이것을위한 멋진 플러그인이 있습니다 : 캐럿 플러그인
그런 다음을 사용하여 위치를 얻 $("#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);
}
커서 위치 외에 선택한 범위가 필요할 수도 있습니다. 다음은 간단한 함수이며 jQuery가 필요하지 않습니다.
function caretPosition(input) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
diff = end - start;
if (start >= 0 && start == end) {
// do cursor position actions, example:
console.log('Cursor Position: ' + start);
} else if (start >= 0) {
// do ranged select actions, example:
console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
}
}
입력이 변경되거나 마우스가 커서 위치를 이동할 때마다 입력에서 호출하려고한다고 가정합니다 (이 경우 jQuery 사용 .on()). 성능상의 이유로 이벤트가 쏟아지는 경우 setTimeout()밑줄과 같은 것을 추가하는 것이 좋습니다 _debounce().
$('input[type="text"]').on('keyup mouseup mouseleave', function() {
caretPosition($(this));
});
그것을 시도하고 싶다면 바이올린이 있습니다 : https://jsfiddle.net/Dhaupin/91189tq7/
const inpT = document.getElementById("text-box");
const inpC = document.getElementById("text-box-content");
// swch gets inputs .
var swch;
// swch if corsur is active in inputs defaulte is false .
var isSelect = false;
var crnselect;
// on focus
function setSwitch(e) {
swch = e;
isSelect = true;
console.log("set Switch: " + isSelect);
}
// on click ev
function setEmoji() {
if (isSelect) {
console.log("emoji added :)");
swch.value += ":)";
swch.setSelectionRange(2,2 );
isSelect = true;
}
}
// on not selected on input .
function onout() {
// الافنت اون كي اب
crnselect = inpC.selectionStart;
// return input select not active after 200 ms .
var len = swch.value.length;
setTimeout(() => {
(len == swch.value.length)? isSelect = false:isSelect = true;
}, 200);
}
<h1> Try it !</h1>
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">
<button onclick="setEmoji()">emogi :) </button>