首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >单击此按钮将特定类的所有元素复制到剪贴板中?

单击此按钮将特定类的所有元素复制到剪贴板中?
EN

Stack Overflow用户
提问于 2016-11-22 15:52:42
回答 1查看 3.1K关注 0票数 1

我知道有很多解决方案可供单击来复制特性,其中最流行的一种似乎是clipboard.js,但我还没有找到只允许您复制具有特定类的元素的解决方案。

例如:

代码语言:javascript
复制
<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>

我如何创建我的脚本来选择所有类“复制文本”并将其复制到我的剪贴板上,但忽略了任何其他内容?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-22 16:31:57

使用document.getElementsByClassName()

代码语言:javascript
复制
<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>
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40746248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档