Replacing text inside textarea without focus

前端 未结 4 1609
慢半拍i
慢半拍i 2021-01-12 23:09

I want to replace selected text(or insert new text after cursor position if nothing is selected). The new text is entered from another textbox.
I want to be able to in

4条回答
  •  爱一瞬间的悲伤
    2021-01-12 23:33

    Alright, correct me where I am wrong.

    1) When text in the textarea is selected, then the button is clicked, the selected text is replaced by the text in the input.
    2) When no text is selected, no matter the cursor position, text is automatically added at the very end of the textarea.

    If those are the only stipulations, then this javascript would suffice, otherwise I need more information on what you want it to do.

    function pasteIntoInput(text) { 
      el=document.getElementById("text");
      el.focus();    
      if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number" && el.selectionStart != el.selectionEnd) { 
        var val = el.value; 
        var selStart = el.selectionStart;
        el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);        
        el.selectionEnd = el.selectionStart = selStart + text.length;
      }
      else
        el.value += text;
    }
    

    Sorry that I cannot be of more assistance, it would be beneficial to understand the use of the function, so I could give the desired action.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题