我知道点击复制功能有很多解决方案,其中一个最受欢迎的似乎是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;并将其复制到我的剪贴板,但遗漏了其他任何东西?
答案 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>