JavaScript将文本区域值复制到剪贴板不起作用



我正在尝试使用javascript将文本区域的内容复制到剪贴板,但它不起作用。当我检查剪贴板时,它是空的。我的Javascript是:

function copyStudentEmails() {
/* Get the text field */
var copyStudentEmail = document.getElementById("student-emails");
/* Select the text field */
copyStudentEmail.select();
copyStudentEmail.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied student emails to clipboard");
}
<textarea rows="5" id="student-emails" class="form-control" disabled required>@studentEmails</textarea>
<button class="btn btn-primary" onclick="copyStudentEmails()">Copy</button>

文本区域的内容是可见的,但复制不起作用。显示javascript函数末尾的警报,但剪贴板为空。

如果省略disabled属性,则会起作用:

function copyStudentEmails() {
/* Get the text field */
var copyStudentEmail = document.getElementById("student-emails");
/* Select the text field */
copyStudentEmail.select();
copyStudentEmail.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied student emails to clipboard");
}
<textarea rows="5" id="student-emails" class="form-control" required>@studentEmails</textarea>
<button class="btn btn-primary" onclick="copyStudentEmails()">Copy</button>

建议对id使用驼色大小写。尝试以下

document.querySelector("textarea").select();
document.execCommand('copy');

此外,从文本区域中删除disabled属性。

最新更新