单击以将特定类的所有元素复制到剪贴板中?

时间:2016-11-22 15:52:43

标签: javascript jquery html clipboard.js

我知道点击复制功能有很多解决方案,其中一个最受欢迎的似乎是clipboard.js但我还没有找到一个解决方案,只允许你复制具有特定类的元素

例如:

<div class="wrapper">
   <div class="copytext">I want to copy this text</div>
   <div class="nocopytext">I don't want to copy this text</div>
   <div class="copytext">I also want to copy this text<div>
</div>
<button>Copy only classes with copytext</button>

如何创建脚本以选择所有类&#34; copytext&#34;并将其复制到我的剪贴板,但遗漏了其他任何东西?

1 个答案:

答案 0 :(得分:3)

使用document.getElementsByClasName()

<div class="wrapper">
   <div class="copytext">I want to copy this text</div>
   <div class="nocopytext">I don't want to copy this text</div>
   <div class="copytext">I also want to copy this text<div>
</div>
<button onclick="copyText()">Copy only classes with copytext</button>
<div id="output"></div>
<script>
function copyText(){
  var outputText = "";
  var targets = document.getElementsByClassName('copytext');
  for(var i = 0; i < targets.length; i++) {
    outputText += targets[i].innerText;
  }
  var output = document.getElementById('output');
  output.innerText = outputText;
  var range = document.createRange();
  range.selectNodeContents(output);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand('copy');
  output.style.display = 'none';
}
</script>