首页 > 解决方案 > 复制文本按钮不起作用,我一直在说空白不是功能

问题描述

所以我试图制作一个按钮,将 ID 为“n”的段落标签复制到剪贴板上,但我不断收到错误消息,说选择不是函数,其他东西不是函数,我在做什么错误的?

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320, initial-scale=1">
<meta charset="utf-8">
<style>
body, html {
min-width: 100%;
min-height: 100%;
margin: 0;
padding: 0;
font: Arial 14px;
}
</style>


<script>
function n() {

var ntext = document.getElementById("n");

ntext.select(); 
ntext.setSelectionRange(0, 99999);

document.execCommand("copy");

alert("could be copied")

}
</script>

</head>
<body>

<input>

<button onclick="n()">
  Click
</button>

<p id="n">
ee
</p>

</body>
</html>      

标签: javascripthtmlcopy-paste

解决方案


这仅适用于输入字段。对你来说,因为你是从一个段落中复制的,你可以试试这个:

<!DOCTYPE html>
<html>
   <body>
      <script>
         function CopyToClipboard(id){
         var r = document.createRange();
         r.selectNode(document.getElementById(id));
         window.getSelection().removeAllRanges();
         window.getSelection().addRange(r);
         document.execCommand('copy');
         window.getSelection().removeAllRanges();
         }
      </script>
      <p id="sample">Hello World</p>
      <a href="#" onclick="CopyToClipboard('sample');return false;">Copy Text</a>
   </body>
</html>

您现在可以根据自己的喜好编辑它。

来源: https ://edupala.com/javascript-clipboard/


推荐阅读