首页 > 解决方案 > 为生成的文本创建复制剪贴板功能

问题描述

我正在创建一个 lorem ipsum 生成器,并从中获得了很多乐趣。但是,我正在尝试创建一个按钮,您可以在其中复制生成的文本。我哪里错了?

我有一个单独的 javascript 文件,可以成功生成文本,只是想知道如何复制它

<body>
<center>
    <h1 class="title">Lorem Ipsum Generator</h1>

    <p class="description">A Harry Potter lorem ipsum generator.</p>

    <form action="/" method="POST">
      <input type="number" class="paragraph-number" name="numberOfParagraphs">
      <input type="submit" value="Expecto Patronum!" class="generate-button">
      <input type="reset" value="clear" class="generate-button">

    </form>  </center>

  <center> 
   <div class="border"><div id="generated-text">
      <div class='placeholder-div'></div>
    </div>
    </div>
    
<button onclick="copyPassage()" class="copy-button">Copy text</button>
    
<script src=/generator.js>
function copyPassage() {
  var copyText = document.getElementById("generated-text");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

标签: javascripthtml

解决方案


你很接近,但是有几件事出了差错。首先,DOM 是按顺序计算的,所以 onclick 处理程序不知道你的函数,因为它是在元素之后声明的;这导致了Uncaught ReferenceError: copyPassage is not defined

接下来,使用错误的方法来实际选择文本。您使用.select()了导致Uncaught TypeError: copyText.select is not a function

相反,对于选择,您应该使用selectAllChildren MDN

在这里查看它的实际效果:

<script>
function copyPassage() {
  var copyText = document.getElementById("generated-text");
  window.getSelection().selectAllChildren(copyText);
  document.execCommand("copy");
  alert("Copied the text: " + copyText.innerText);
}
</script>
<button onclick="copyPassage()" class="copy-button">Copy text</button>
<div class="border">
    <div id="generated-text">
         <div class='placeholder-div'>Harry Potter</div>
    </div>
</div>
    


推荐阅读