繁体   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