简体   繁体   English

复制到剪贴板 HTML

[英]Copy to clipboard HTML

I'm creating a small site to generate amazon affiliate link using asin I used a small script to generate the URL but I'm looking to copy the output in the clipboard directly.我正在创建一个小站点来使用 asin 生成亚马逊会员链接我使用了一个小脚本来生成 URL,但我希望直接在剪贴板中复制输出。

I looked around without finding a suitable solution for my problem.我环顾四周,没有找到适合我的问题的解决方案。

Here is the script I'm using to generate the URL.这是我用来生成 URL 的脚本。

The HTML part is just an input and a button. 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>

If you want a simple solution you'll have to create another function once the link is already created and up in the website.如果您想要一个简单的解决方案,您必须在链接已经创建并在网站中创建后创建另一个函数。

The new function will use the document.getElementById() function and the .select() method新函数将使用document.getElementById()函数和.select()方法

example and implementation can be found here:示例和实现可以在这里找到:

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

You can use the Clipboard API in the navigator for this purpose.为此,您可以在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>

Here is the simple solution:这是简单的解决方案:

/* 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM