function copy_text_fun() { //getting text from P tag var copyText = document.getElementById("copy_txt"); // creating textarea of html var input = document.createElement("textarea"); //adding p tag text to textarea input.value = copyText.textContent; document.body.appendChild(input); input.select(); document.execCommand("Copy"); // removing textarea after copy input.remove(); alert(input.value);}<p id="copy_txt">hi</p><button onclick="copy_text_fun()">Copy</button>
请试试这个。也许它会为你工作。 function myFunction() { /* Get the text field */ var copyText = document.getElementById("myInput"); /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /*For mobile devices*/ /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied the text: " + copyText.value); } <input type="text" value="Hello World" id="myInput"> <button onclick="myFunction()">Copy text</button>