텍스트 상자가 많은 페이지가 있습니다. 누군가가 링크를 클릭하면 커서가있는 곳에 단어가 삽입되거나 포커스가있는 텍스트 상자에 추가되기를 원합니다.
예를 들어, 커서 / 포커스가 ‘apple’이라는 텍스트 상자에 있고 ‘[email]’이라는 링크를 클릭하면 텍스트 상자에 ‘apple bob@example.com’이라고 말하고 싶습니다.
어떻게해야합니까? 초점이 라디오 / 드롭 다운 / 비 텍스트 상자 요소에있을 경우 어떻게됩니까? 텍스트 상자에 마지막으로 초점을 맞춘 것을 기억할 수 있습니까?
답변
function insertAtCaret(areaId, text) {
var txtarea = document.getElementById(areaId);
if (!txtarea) {
return;
}
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
"ff" : (document.selection ? "ie" : false));
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart('character', -txtarea.value.length);
strPos = range.text.length;
} else if (br == "ff") {
strPos = txtarea.selectionStart;
}
var front = (txtarea.value).substring(0, strPos);
var back = (txtarea.value).substring(strPos, txtarea.value.length);
txtarea.value = front + text + back;
strPos = strPos + text.length;
if (br == "ie") {
txtarea.focus();
var ieRange = document.selection.createRange();
ieRange.moveStart('character', -txtarea.value.length);
ieRange.moveStart('character', strPos);
ieRange.moveEnd('character', 0);
ieRange.select();
} else if (br == "ff") {
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
<textarea id="textareaid"></textarea>
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
답변
더 짧은 버전 일수록 이해하기 쉬울 수 있습니까?
jQuery("#btn").on('click', function() {
var $txt = jQuery("#txt");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
var txtToAdd = "stuff";
$txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />
jquery로 포인터의 현재 위치에서 텍스트 상자에 텍스트를 추가하는 방법 에 대한 응답으로 이것을 썼습니다 .
답변
George Claghorn의 승인 된 답변은 단순히 커서 위치에 텍스트를 삽입하는 데 효과적이었습니다. 사용자가 텍스트를 선택했지만 해당 텍스트를 바꾸려면 (대부분의 텍스트에서 기본 환경) ‘back’변수를 설정할 때 약간 변경해야합니다.
또한 이전 버전의 IE를 지원할 필요가없는 경우 최신 버전은 textarea.selectionStart를 지원하므로 모든 브라우저 감지 및 IE 특정 코드를 제거 할 수 있습니다.
다음은 최소한 Chrome 및 IE11에서 작동하며 선택한 텍스트 교체를 처리하는 단순화 된 버전입니다.
function insertAtCaret(areaId, text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var caretPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0, caretPos);
var back = (txtarea.value).substring(txtarea.selectionEnd, txtarea.value.length);
txtarea.value = front + text + back;
caretPos = caretPos + text.length;
txtarea.selectionStart = caretPos;
txtarea.selectionEnd = caretPos;
txtarea.focus();
txtarea.scrollTop = scrollPos;
}
답변
위의 코드는 IE에서 작동하지 않았습니다. 이 답변을 기반으로 한 코드가 있습니다.
나는 getElementById
다른 방식으로 요소를 참조 할 수 있도록 꺼내었다 .
function insertAtCaret(element, text) {
if (document.selection) {
element.focus();
var sel = document.selection.createRange();
sel.text = text;
element.focus();
} else if (element.selectionStart || element.selectionStart === 0) {
var startPos = element.selectionStart;
var endPos = element.selectionEnd;
var scrollTop = element.scrollTop;
element.value = element.value.substring(0, startPos) +
text + element.value.substring(endPos, element.value.length);
element.focus();
element.selectionStart = startPos + text.length;
element.selectionEnd = startPos + text.length;
element.scrollTop = scrollTop;
} else {
element.value += text;
element.focus();
}
}
input{width:100px}
label{display:block;margin:10px 0}
<label for="in2copy">Copy text from: <input id="in2copy" type="text" value="x"></label>
<label for="in2ins">Element to insert: <input id="in2ins" type="text" value="1,2,3" autofocus></label>
<button onclick="insertAtCaret(document.getElementById('in2ins'),document.getElementById('in2copy').value)">Insert</button>
편집 : 실행중인 스 니펫을 추가했습니다 .jQuery가 사용되지 않습니다 .
답변
@quick_sliv 답변 사용 :
function insertAtCaret(el, text) {
var caretPos = el.selectionStart;
var textAreaTxt = el.value;
el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
};
답변
JQuery와 JavaScript를 통해 TextBox의 현재 커서 위치에 일부 텍스트를 삽입하는 방법
방법
- 현재 커서 위치 찾기
- 복사 할 텍스트 가져 오기
- 저기에 텍스트를 설정
- 커서 위치 업데이트
여기에 2 개의 TextBox와 버튼이 있습니다. 텍스트 상자에서 특정 위치를 클릭 한 다음 버튼을 클릭하여 다른 텍스트 상자의 텍스트를 이전 텍스트 상자의 위치에 붙여 넣습니다.
여기서 주요 문제는 텍스트를 붙여 넣을 현재 커서 위치를 얻는 것입니다.
//Textbox on which to be pasted
<input type="text" id="txtOnWhichToBePasted" />
//Textbox from where to be pasted
<input type="text" id="txtFromWhichToBePasted" />
//Button on which click the text to be pasted
<input type="button" id="btnInsert" value="Insert"/>
<script type="text/javascript">
$(document).ready(function () {
$('#btnInsert').bind('click', function () {
var TextToBePasted = $('#txtFromWhichToBePasted').value;
var ControlOnWhichToBePasted = $('#txtOnWhichToBePasted');
//Paste the Text
PasteTag(ControlOnWhichToBePasted, TextToBePasted);
});
});
//Function Pasting The Text
function PasteTag(ControlOnWhichToBePasted,TextToBePasted) {
//Get the position where to be paste
var CaretPos = 0;
// IE Support
if (document.selection) {
ControlOnWhichToBePasted.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ControlOnWhichToBePasted.selectionStart || ControlOnWhichToBePasted.selectionStart == '0')
CaretPos = ControlOnWhichToBePasted.selectionStart;
//paste the text
var WholeString = ControlOnWhichToBePasted.value;
var txt1 = WholeString.substring(0, CaretPos);
var txt2 = WholeString.substring(CaretPos, WholeString.length);
WholeString = txt1 + TextToBePasted + txt2;
var CaretPos = txt1.length + TextToBePasted.length;
ControlOnWhichToBePasted.value = WholeString;
//update The cursor position
setCaretPosition(ControlOnWhichToBePasted, CaretPos);
}
function setCaretPosition(ControlOnWhichToBePasted, pos) {
if (ControlOnWhichToBePasted.setSelectionRange) {
ControlOnWhichToBePasted.focus();
ControlOnWhichToBePasted.setSelectionRange(pos, pos);
}
else if (ControlOnWhichToBePasted.createTextRange) {
var range = ControlOnWhichToBePasted.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
답변
현재 커서 위치에 텍스트를 추가하려면 두 단계가 필요합니다.
- 현재 커서 위치에 텍스트 추가
- 현재 커서 위치 업데이트
데모 : https://codepen.io/anon/pen/qZXmgN
Chrome 48, Firefox 45, IE 11 및 Edge 25에서 테스트
JS :
function addTextAtCaret(textAreaId, text) {
var textArea = document.getElementById(textAreaId);
var cursorPosition = textArea.selectionStart;
addTextAtCursorPosition(textArea, cursorPosition, text);
updateCursorPosition(cursorPosition, text, textArea);
}
function addTextAtCursorPosition(textArea, cursorPosition, text) {
var front = (textArea.value).substring(0, cursorPosition);
var back = (textArea.value).substring(cursorPosition, textArea.value.length);
textArea.value = front + text + back;
}
function updateCursorPosition(cursorPosition, text, textArea) {
cursorPosition = cursorPosition + text.length;
textArea.selectionStart = cursorPosition;
textArea.selectionEnd = cursorPosition;
textArea.focus();
}
HTML :
<div>
<button type="button" onclick="addTextAtCaret('textArea','Apple')">Insert Apple!</button>
<button type="button" onclick="addTextAtCaret('textArea','Mango')">Insert Mango!</button>
<button type="button" onclick="addTextAtCaret('textArea','Orange')">Insert Orange!</button>
</div>
<textarea id="textArea" rows="20" cols="50"></textarea>
