单击以将特定 class 的所有元素复制到剪贴板?
Click to copy all elements of a specific class into the clipboard?
我知道点击复制功能有很多解决方案,最受欢迎的解决方案之一似乎是 clipboard.js,但我还没有找到允许您仅复制具有具体 class.
例如:
<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>
如何创建我的脚本 select 所有 classes "copytext" 并将其复制到我的剪贴板但不保留任何其他内容?
使用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>
我知道点击复制功能有很多解决方案,最受欢迎的解决方案之一似乎是 clipboard.js,但我还没有找到允许您仅复制具有具体 class.
例如:
<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>
如何创建我的脚本 select 所有 classes "copytext" 并将其复制到我的剪贴板但不保留任何其他内容?
使用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>