Copy text from to clipboard

前端 未结 3 1642
迷失自我
迷失自我 2020-12-29 08:02

I\'ve been trying to copy the innerContent of a to my clipboard without success:

HTML



        
3条回答
  •  自闭症患者
    2020-12-29 08:12

    You could do this: create a temporary text area and append it to the page, then add the content of the span element to the text area, copy the value from the text area and remove the text area.

    Because of some security restrictions you can only execute the Copy command if the user interacted with the page, so you have to add a button and copy the text after the user clicks on the button.

    document.getElementById("cp_btn").addEventListener("click", copy_password);
    
    function copy_password() {
        var copyText = document.getElementById("pwd_spn");
        var textArea = document.createElement("textarea");
        textArea.value = copyText.textContent;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand("Copy");
        textArea.remove();
    }
    Test
    

提交回复
热议问题