簡體   English   中英

復制到剪貼板 HTML

[英]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()方法

示例和實現可以在這里找到:

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

為此,您可以在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.

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