首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Javascript复制到剪贴板功能

使用Javascript复制到剪贴板功能
EN

Stack Overflow用户
提问于 2018-07-28 06:56:05
回答 1查看 123关注 0票数 1

这是JavaScript的新手,我正在尝试让一个按钮将代码中的一些文本复制到剪贴板。这似乎不管用..请让我知道我错过了什么。谢谢!

代码语言:javascript
复制
<!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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-28 07:13:14

它不能工作的原因是因为你不能对一个可变的.select()进行操作;所以当你复制一个document.execCommand(“复制”)时,你要复制任何其他选定的文本,试着把这些东西放到输入框中,然后再尝试.select();

代码语言:javascript
复制
<!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>

如果要隐藏文本框,请执行以下操作

代码语言:javascript
复制
<!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>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51566502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档