[英]Copy to clipboard HTML
我正在创建一个小站点来使用 asin 生成亚马逊会员链接我使用了一个小脚本来生成 URL,但我希望直接在剪贴板中复制输出。
我环顾四周,没有找到适合我的问题的解决方案。
这是我用来生成 URL 的脚本。
HTML 部分只是一个输入和一个按钮。
<script>
function myFunction() {
let userInput = document.querySelector("#userInput");
let url = document.querySelector("#url");
url.innerHTML = "https://www.amazon.it/dp/" + userInput.value + "/ref=nosim?tag=altpe-21";
}
</script>
如果您想要一个简单的解决方案,您必须在链接已经创建并在网站中创建后创建另一个函数。
新函数将使用document.getElementById()
函数和.select()
方法
示例和实现可以在这里找到:
为此,您可以在navigator
器中使用Clipboard
API。
<script>
function myFunction() {
let userInput = document.querySelector("#userInput");
let url = document.querySelector("#url");
let output = "https://www.amazon.it/dp/" + userInput.value + "/ref=nosim?tag=altpe-21";
url.innerHTML = output;
navigator.permissions.query({name: "clipboard-write"}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.writeText(output);
}
});
}
</script>
这是简单的解决方案:
/* 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 */
navigator.clipboard.writeText(copyText.value);
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.