我想创建一个简单的函数,将文本添加到用户光标位置的文本区域中。它需要是一个干净的功能。只是基础知识。我可以弄清楚其余的。
如何在当前光标位置的textarea中插入文本?
IT技术
javascript
textarea
                    2021-01-28 13:57:46
                
                    
                
            
        6个回答
            输入元素的使用selectionStart/selectionEnd 属性(也适用<textarea>)
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);
});
为了正确的 Javascript
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'));
一个简单的解决方案,适用于 firefox、chrome、opera、safari 和 edge,但可能不适用于旧的 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功能允许您用提供的文本替换当前选择,或者如果没有选择则在光标位置插入文本。据我所知,它仅受 Firefox 支持。
对于其他浏览器,有“insertText”命令,它只影响当前聚焦的 html 元素,并且具有相同的行为 setRangeText
部分灵感来自这篇文章
其它你可能感兴趣的问题