[javascript] 현재 커서 위치에서 텍스트 영역에 텍스트를 삽입하는 방법은 무엇입니까?

사용자 커서 위치의 텍스트 영역에 텍스트를 추가하는 간단한 함수를 만들고 싶습니다. 깨끗한 기능이 필요합니다. 기본입니다. 나머지는 알아낼 수 있습니다.



답변

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //MOZILLA and others
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
            + myValue
            + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}


답변

이 스 니펫은 jQuery 1.9+의 몇 줄에서 도움이 될 수 있습니다. http://jsfiddle.net/4MBUG/2/

$('input[type=button]').on('click', function() {
    var cursorPos = $('#text').prop('selectionStart');
    var v = $('#text').val();
    var textBefore = v.substring(0,  cursorPos);
    var textAfter  = v.substring(cursorPos, v.length);

    $('#text').val(textBefore + $(this).val() + textAfter);
});


답변

적절한 자바 스크립트를 위해

HTMLTextAreaElement.prototype.insertAtCaret = function (text) {
  text = text || '';
  if (document.selection) {
    // IE
    this.focus();
    var sel = document.selection.createRange();
    sel.text = text;
  } else if (this.selectionStart || this.selectionStart === 0) {
    // Others
    var startPos = this.selectionStart;
    var endPos = this.selectionEnd;
    this.value = this.value.substring(0, startPos) +
      text +
      this.value.substring(endPos, this.value.length);
    this.selectionStart = startPos + text.length;
    this.selectionEnd = startPos + text.length;
  } else {
    this.value += text;
  }
};


답변

새로운 답변 :

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText

그래도 브라우저 지원에 대해 잘 모르겠습니다.

Chrome 81에서 테스트되었습니다.

function typeInTextarea(newText, el = document.activeElement) {
  const [start, end] = [el.selectionStart, el.selectionEnd];
  el.setRangeText(newText, start, end, 'select');
}

document.getElementById("input").onkeydown = e => {
  if (e.key === "Enter") typeInTextarea("lol");
}
<input id="input" />
<br/><br/>
<div>Press Enter to insert "lol" at caret.</div>
<div>It'll replace a selection with the given text.</div>

이전 답변 :

Erik Pukinskis의 대답에 대한 순수한 JS 수정 :

function typeInTextarea(newText, el = document.activeElement) {
  const start = el.selectionStart
  const end = el.selectionEnd
  const text = el.value
  const before = text.substring(0, start)
  const after  = text.substring(end, text.length)
  el.value = (before + newText + after)
  el.selectionStart = el.selectionEnd = start + newText.length
  el.focus()
}

document.getElementById("input").onkeydown = e => {
  if (e.key === "Enter") typeInTextarea("lol");
}
<input id="input" />
<br/><br/>
<div>Press Enter to insert "lol" at caret.</div>

Chrome 47, 81 및 Firefox 76에서 테스트되었습니다.

자동 완성 또는 유사한 효과를 위해 동일한 필드에 입력하는 동안 현재 선택한 텍스트의 값을 변경 document.activeElement하려면 첫 번째 매개 변수로 전달 합니다.

이 작업을 수행하는 가장 우아한 방법은 아니지만 매우 간단합니다.

사용 예 :

typeInTextarea('hello');
typeInTextarea('haha', document.getElementById('some-id'));


답변

파이어 폭스, 크롬, 오페라, 사파리, 엣지에서 작동하지만 아마도 오래된 IE 브라우저에서는 작동하지 않을 간단한 솔루션입니다.

  var target = document.getElementById("mytextarea_id")

  if (target.setRangeText) {
     //if setRangeText function is supported by current browser
     target.setRangeText(data)
  } else {
    target.focus()
    document.execCommand('insertText', false /*no UI*/, data);
  }
}

setRangeText기능을 사용하면 현재 선택을 제공된 텍스트로 대체하거나 선택하지 않은 경우 커서 위치에 텍스트를 삽입 할 수 있습니다. 내가 아는 한 파이어 폭스에서만 지원됩니다.

다른 브라우저의 경우 현재 포커스가있는 html 요소에만 영향을 미치고 다음과 동일한 동작을하는 “insertText”명령이 있습니다. setRangeText

이것에서 부분적으로 영감을 얻음 기사에서


답변

Rab의 답변은 훌륭하게 작동하지만 Microsoft Edge에는 적용되지 않으므로 Edge에도 약간의 적응을 추가했습니다.

https://jsfiddle.net/et9borp4/

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    // Microsoft Edge
    else if(window.navigator.userAgent.indexOf("Edge") > -1) {
      var startPos = myField.selectionStart;
      var endPos = myField.selectionEnd;

      myField.value = myField.value.substring(0, startPos)+ myValue
             + myField.value.substring(endPos, myField.value.length);

      var pos = startPos + myValue.length;
      myField.focus();
      myField.setSelectionRange(pos, pos);
    }
    //MOZILLA and others
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
            + myValue
            + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}


답변

저는 간단한 자바 스크립트를 좋아하고 보통 jQuery를 가지고 있습니다. mparkuk를 기반으로 내가 생각해 낸 것은 다음과 같습니다 .

function typeInTextarea(el, newText) {
  var start = el.prop("selectionStart")
  var end = el.prop("selectionEnd")
  var text = el.val()
  var before = text.substring(0, start)
  var after  = text.substring(end, text.length)
  el.val(before + newText + after)
  el[0].selectionStart = el[0].selectionEnd = start + newText.length
  el.focus()
}

$("button").on("click", function() {
  typeInTextarea($("textarea"), "some text")
  return false
})

데모 : http://codepen.io/erikpukinskis/pen/EjaaMY?editors=101