簡體   English   中英

JavaScript 將 textarea 值復制到剪貼板不起作用

[英]JavaScript copy textarea value to clipboard not working

我正在嘗試使用 javascript 將 textarea 的內容復制到剪貼板,但它不起作用。 當我檢查剪貼板時它是空的。 我的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>

textarea 的內容是可見的,但復制不起作用。 顯示 javascript 函數末尾的警報,但剪貼板為空。

建議對 id 使用駝峰式外殼。 試試下面的

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

此外,從文本區域中刪除disabled屬性。

如果您省略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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM