簡體   English   中英

如何將文本復制到剪貼板 HTML?

[英]How to copy text to clipboard HTML?

我有一個包含鏈接的 set p 元素。 我希望用戶單擊一個按鈕,它會獲取 p 元素的值並將其復制到用戶的剪貼板。

 function copy() { document.getElementById("link").copy; }
 #link { color: blue; }
 <p id="link" onclick="copy()">https://www.spotify.com/us/</p>

 function copy() { var copyText = document.getElementById("link").innerText; var elem = document.createElement("textarea"); document.body.appendChild(elem); elem.value = copyText; elem.select(); document.execCommand("copy"); document.body.removeChild(elem); alert("Copied the text"); }
 #link { color: blue; }
 <p id="link" onclick="copy()">https://www.spotify.com/us/</p>

你的副本 function 可以如下

function copy() {
  var copyText = document.getElementById("link").innerText;
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = copyText;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  alert("Copied the text");
}

試試這個作為副本 function

var text =  document.getElementById("link");
text.select();
document.execCommand("copy);

您可以使用input復制剪貼板上的文本

 function copy() { /* Get the text field */ var copyText = document.getElementById("link"); /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /*For mobile devices*/ /* Copy the text inside the text field */ document.execCommand("copy"); console.log("copied;"); }
 <input id="link" onclick="copy()" value="https://www.spotify.com/us/">

或者如果你想使用 p 那么你可以使用這個技巧

 function copy() { /* Get the text field */ var copyText = document.getElementById("link"); var copyP = document.getElementById("link_p"); copyText.value=copyP.innerHTML; /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /*For mobile devices*/ /* Copy the text inside the text field */ document.execCommand("copy"); console.log("copied;"); }
 <input type="text" id="link" value="" style="display:none"> <p id="link_p" onclick="copy()">text</p>

 function copy() { document.getElementById("link").copy; }
 #link { color: blue; }
 <p id="link" onclick="copy()">https://www.spotify.com/us/</p>

暫無
暫無

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

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