gpt4 book ai didi

javascript - 如何将变量复制到剪贴板

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:28 24 4
gpt4 key购买 nike

如何将变量复制到剪贴板?

它总是返回:

Uncaught TypeError: copyText.select is not a function

代码

function copy() {
var allDesCode2 = document.getElementsByClassName("desCode2");
var copyText = "ABC";
for(var i=0; i<allDesCode2.length; i++) {
copyText += allDesCode2[i].innerHTML;
}
copyText.select();
document.execCommand("copy");
}

最佳答案

下面的copy() 函数可以帮助从变量中复制字符串。您可以在纯 JavaScript 中使用此方法无需任何库的帮助,例如 jQuery .

function copy() {

var copyText = "Hooray ! I will be copied";
var el = document.createElement('textarea');
el.value = copyText;
el.setAttribute('readonly', '');
el.style = {
position: 'absolute',
left: '-9999px'
};
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
<button onclick="copy()">Copy</button>

关于javascript - 如何将变量复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55177513/

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