我知道有很多解决方案可供单击来复制特性,其中最流行的一种似乎是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>我如何创建我的脚本来选择所有类“复制文本”并将其复制到我的剪贴板上,但忽略了任何其他内容?
发布于 2016-11-22 16:31:57
使用document.getElementsByClassName()
<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>https://stackoverflow.com/questions/40746248
复制相似问题