javascript textarea处理中的复制剪切粘贴功能

时间:2019-07-04 15:03:07

标签: javascript

我正在尝试在以下位置编写这些功能:

https://jsfiddle.net/7rqgkozp/50/

HTML:

<textarea id="text_element" style="width:100%;height:200px" >Copy this ss!</textarea>
<br>
<button onclick="copyToClipboard('text_element')">
    Copy to clipboard
</button>
<button onclick="cutToClipboard('text_element')">
    cut to clipboard
</button>
<button onclick="pastefromclipboard('text_element')">
    paste
</button>

Javascript:

function copyToClipboard(elementId) {


  // Create an auxiliary hidden input
     var Tselected = getSel();  // Execute the copy command


  var aux = document.createElement("input");
  aux.setAttribute("type","text");
  aux.setAttribute("value",Tselected);
  aux.setAttribute("id","Tselected");
  document.body.appendChild(aux);



  // Highlight the content
  aux.select();

   document.execCommand("copy");



}


function cutToClipboard(elementId) {

     var Tselected = getSel(); //get selected text
  // Create an auxiliary hidden input

  var aux = document.createElement("input");
  aux.setAttribute("type","text");
  aux.setAttribute("value",Tselected);
  aux.setAttribute("id","Tselected");
  document.body.appendChild(aux);



  // Highlight the content
  aux.select();


     var myInput = document.getElementById("text_element");
var myInputVal = myInput.value;
    var newvalue =      myInputVal.replace(Tselected, "");
    myInput.value = newvalue;

   //
   document.execCommand("copy");



}


function pastefromclipboard(){
    var Tselected = document.getElementById("Tselected");
    var TselectedVal = Tselected.value;

      var myInput = document.getElementById("text_element");
   document.execCommand("paste");

   myInput.value += TselectedVal;
     document.body.removeChild(Tselected);
document.getElementById("my-element").remove();


}

function getSel() // javascript
{
    // obtain the object reference for the <textarea>
    var txtarea = document.getElementById("text_element");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    // obtain the selected text
    var sel = txtarea.value.substring(start, finish);
    // do something with the selected content


    return sel;

}

但是我只能将文本复制并粘贴到textarea的末尾,但是我需要将其粘贴到用户单击textarea的位置

代码已更新

1 个答案:

答案 0 :(得分:1)

通过将粘贴功能更改为:

来解决此问题
function pastefromclipboard() {
  var Tselected = document.getElementById("Tselected");
  var TselectedVal = Tselected.value;

  var myInput = document.getElementById("text_element");
  document.execCommand("paste");



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




  document.body.removeChild(Tselected);
  document.getElementById("my-element").remove();


}