簡體   English   中英

我在 JavaScript 中復制到剪貼板代碼不起作用

[英]my copy to clipboard code in JavaScript doesn't work

正如您從我的問題中猜到的那樣,並且您將通過查看我的代碼來解釋,我是初學者。 這是我嘗試用 javascript 編寫的第一個真正的應用程序,我很想知道為什么它不起作用?

var button = document.getElementById("button");
var text = document.getElementById("text");
function button() {
 text.select();
 text.setSelectionRange(0, 99999); 
navigator.clipboard.writeText(text.value);
alert("you copied this text");
}

按鈕是 html 中的 onclick 事件,文本是 html 中的輸入。 非常感謝您

如前所述, writeText是一個承諾,但Clipboard API需要許可。 檢查此是否授予權限

 function myFunction() { /* Get the text field */ var copyText = document.getElementById("myText"); /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /* For mobile devices */ /* Copy the text inside the text field */ navigator.clipboard.writeText(copyText.value).then(function() { alert("Copied to clipboard successfully!"); }, function(error) { alert("ERROR:\\n"+error); });; } async function CheckPermission(){ const readPerm = await navigator.permissions.query({name: 'clipboard-read', allowWithoutGesture: false }); const writePerm = await navigator.permissions.query({name: 'clipboard-write', allowWithoutGesture: false }); // Will be 'granted', 'denied' or 'prompt': alert('Read: '+readPerm.state+'\\nWrite: '+writePerm.state); }
 <input type="text" value="ASDF" id="myText"> <button onclick="myFunction()">Copy text</button><br><br> <button onclick="CheckPermission()">Check Permission</button>

如果是這樣,需要征得許可。 更多信息在這里

我不知道我是否應該寫這個作為答案或什么。 但無論如何我重寫了代碼,結果是這樣的:

var text = document.getElementById("text");
var button = document.getElementById("button");

function textinput(selector) {
text.select();
text.setSelectionRange(0, 99999); 
}
function buttonholder() {
navigator.clipboard.writeText(text.value);
}
button.addEventListener("click",buttonholder);

謝謝大家回復。 復制部分正在工作並且沒問題。 但是在上面的代碼中,如您所見,我創建了一個可以選擇輸入的函數。 但我想知道我該怎么稱呼它? 我嘗試了一些典型的代碼,但無法解決。再次感謝您的幫助

您已經使用“function”作為按鈕元素的標識符。 因此,只需更改您的函數名稱(例如 buttonHandler),它就會起作用。

答案代碼:

var button = document.getElementById("button");
var text = document.getElementById("text");
function buttonHandler() { 
navigator.clipboard.writeText(text.value);
alert(`you copied this ${text.value}`);
}

附注。 不要忘記更改 HTML 文件中函數的名稱。

暫無
暫無

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

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