【问题标题】:Create a copy clipboard function for generated text为生成的文本创建复制剪贴板功能
【发布时间】:2019-01-15 19:07:35
【问题描述】:

我正在创建一个 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>

【问题讨论】:

  • 检查this answer
  • 您不应该在该脚本块上有 src 属性。那应该是两个单独的脚本块,一个为空的,带有src 属性,另一个只是其中的javascript。

标签: javascript html


【解决方案1】:

你很接近,但是有几件事出了差错。首先,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>
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多