3 回答

TA貢獻1813條經驗 獲得超2個贊
您可以使用navigator.clipboard.writeText將文本復制到剪貼板。
function copy(input) {
if (navigator.clipboard) {
navigator.clipboard.writeText(input).then(() => {
console.log('Copied to clipboard successfully.');
}, (err) => {
console.log('Failed to copy the text to clipboard.', err);
});
} else if (window.clipboardData) {
window.clipboardData.setData("Text", input);
}
}
<p>Text To Copy = hi <button type="button" onclick="copy('hi')">click to copy</button></p>

TA貢獻1852條經驗 獲得超7個贊
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>

TA貢獻1735條經驗 獲得超5個贊
請試試這個。也許它會為你工作。
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>
添加回答
舉報