JavaScript copy to clipboard not working

前端 未结 5 1107
感动是毒
感动是毒 2021-02-12 22:11

I have a function in my script that gives me an error. The function purpose is to copy text from static panel(not textbox or input) with onClick event.

Uncaught

5条回答
  •  走了就别回头了
    2021-02-12 22:23

    hi so I looked into it and since you are not using a textInput you cannot just use the .select()function. I borrowed some code from a fellow stack overflow developer Jason on how to highlight an item in javaScript

    selecting text in an element akin to highlighting with your mouse.

    function selectedText(element)(){

    var doc = document,
    text = doc.getElementById(element)
    range, selection;
    
    if(doc.body.createTextRange){ 
     range = document.body.createTextRange();
     range.moveToElementText(text);
     range.select(); 
    }
    else if(window.getSelection){
      selection = window.getSelection();
      range = document.createRange();
      range.selectNodeContents(text);
      selection.removeAllRanges();
      selection.addRange(range);   
    }
    
    return range;
    

    I then modified it to return the range. and with that all you would have to do is

    document.onclick = function(e){
      if(e.target.className === 'click'){
    
          var copytext = SelectText('display');
          document.execCommand("copy");
          alert("Copied the text: " + copytext);
       }
    }
    

    the key part here is that the string passed in to .execCommand() is lower case 'copy'

提交回复
热议问题