gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:41:53 25 4
gpt4 key购买 nike

我知道点击复制功能有很多解决方案,最流行的解决方案之一似乎是 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>

我如何创建我的脚本来选择所有类“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>

关于javascript - 单击以将特定类的所有元素复制到剪贴板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com