JavaScript copy to clipboard not working

前端 未结 5 1111
感动是毒
感动是毒 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:20

    This will allow you to copy the text of an element. Though I have not tested it with complicated layout.

    If you want to use this then remove the alerts and provide a better way to let the user know the content was copied.

    SAFARI: This does not work on Safari before version 10.0. But as of Safari 10.0 this now works.

    function copyText(element) {
      var range, selection, worked;
    
      if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
      } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
      }
      
      try {
        document.execCommand('copy');
        alert('text copied');
      }
      catch (err) {
        alert('unable to copy text');
      }
    }

    Text Sample

    If you want to use this on an or