Hidden element won't copy to clipboard

后端 未结 4 1882
闹比i
闹比i 2021-01-13 19:20

I am trying to add button to copy simple text string but without success.

4条回答
  •  无人共我
    2021-01-13 19:58

    You cannot select a hidden element.

    Best way is to copy the value in the element to another visible element.

    As you can see, I created a textarea with an absolute position and set the top and left to -9999px. So now, you can copy the value in the hidden element to the textarea and then cope the value in the textarea to the clipboard

    function kopiraj() {
      var copyFrom = document.getElementById("toCopy"); //Value to copy
      var copyTo  = document.getElementById("valueToCopy"); //Visible element to copy the value to
      
      copyTo.value = copyFrom.value; //Fill the visible element with the value to copy 
      copyTo.select(); //Select the value
      document.execCommand("Copy"); //Copy
      copyTo.value = ""; //Empty the visible element after copy
    }
    .valueToCopy{
      position: absolute;
      top: -9999px;
      left: -9999px;
      opacity: 0;
    }
    
    
    
    

提交回复
热议问题