[英]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.