从剪贴板中的多个 div 复制多个文本

Copy multiple texts from multiple divs in clipboard

所以我在 HTML 文件中嵌套了 div 标签。我试图从每个 div 标签中复制某些文本。搜索了几个小时后,我终于找到了有效的 。解决方案如下:

    <html>
        <body>
            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
            <script>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    range.selectNode(document.getElementById("a"));
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    document.execCommand("copy");
                    window.getSelection().removeAllRanges();// to deselect
                }
            </script>
        </body>
    </html>

但由于它使用的是 id,因此它只适用于第一个 div。然后我将 id 更改为 class 但是之前找到的解决方案不起作用。我的 HTML 文件如下:

<div>
  <div onclick="copyTextToClipboard()">
    <span>My favorite actor is <span class="text_to_copy">Robert Downey, Jr.</span></span>
  </div>
  <div onclick="copyTextToClipboard()">
    <span>My favorite actor is <span class="text_to_copy">Tom Cruise</span></span>
  </div>
  <div onclick="copyTextToClipboard()">
    <span>My favorite actor is <span class="text_to_copy">Hugh Jackman</span></span>
  </div>
  <div onclick="copyTextToClipboard()">
    <span>My favorite actor is <span class="text_to_copy">Ryan Gosling</span></span>
  </div>
</div>

在对我找到的解决方案发表评论后,他建议我查看 Range.setStart()Range.setEnd()。但我只是不知道如何应用这些,因为我对 Javascript.

还比较陌生

还有几个 span 标签用于不同的 类 样式。

我对你的代码做了一些修改,请看一下,看看是否有帮助。

var elements = document.getElementsByClassName("parentDiv");

Array.from(elements).forEach(function(element) {
  element.addEventListener('click', copyTextToClipboard);
});

function copyTextToClipboard() {
  var selection = window.getSelection();
  var range = document.createRange();
  let dataToCopy = this.getElementsByClassName('text_to_copy');
  range.selectNodeContents(dataToCopy[0]);
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand("Copy");
  window.getSelection().removeAllRanges()
}
<html>

<body>
  <div>
    <div class="parentDiv">
      <span>My favorite actor is <span class="text_to_copy">Robert Downey, Jr.</span></span>
    </div>
    <div class="parentDiv">
      <span>My favorite actor is <span class="text_to_copy">Tom Cruise</span></span>
    </div>
    <div class="parentDiv">
      <span>My favorite actor is <span class="text_to_copy">Hugh Jackman</span></span>
    </div>
    <div class="parentDiv">
      <span>My favorite actor is <span class="text_to_copy">Ryan Gosling</span></span>
    </div>
  </div>
</body>

</html>