简体   繁体   English

使用Java复制到剪贴板功能

[英]Copy To Clipboard Function With Javascript

New to JavaScript and I'm trying to have a button copy some text in the code to the clipboard. JavaScript的新功能,我试图让按钮将代码中的一些文本复制到剪贴板。 This doesn't seem to work.. Please let me know what I'm missing. 这似乎无效。.请让我知道我所缺少的。 Thanks! 谢谢!

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Copy text</button>

<script>
function myFunction() {
  var copyText = "myText";
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

</body>
</html>

The reason it wasnt working is because you cant do to a varaible .select(); 它不起作用的原因是因为您不能对变量.select();进行操作。 so when you do a document.execCommand("copy"); 因此,当您执行document.execCommand(“ copy”);时, your copying any other selected text try putting the stuff in a input box and then try .select(); 您复制任何其他选定的文本时,请尝试将内容放入输入框,然后尝试.select();。

<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText"> </input>
<button onclick="myFunction()">Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

</body>
</html>

and if you want to hide the textbox do 如果要隐藏文本框

<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText" style="display:none;"> </input>
<button onclick="myFunction()">Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.style = "display:inline";
  copyText.select();
  copyText.style = "display:none";
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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