我希望当我按下按钮时它会复制“你好” 但我收到此错误: copyText.select 不是函数
如何解决?
<html>
<head>
</head>
<body>
<span id="aaa">hello</span>
<button onclick="copy('#aaa')">copy</button>
<script>
function copy(text)
{
var copyText = text;
copyText.select();
document.execCommand("copy");
console.log(document.getElementById('text'));
}
</script>
</body>
最佳答案
您无法使用选择功能选择跨度的文本。您必须使用范围文本的值创建一个临时输入。使用 select() 选择输入中的值并复制文本,然后删除输入
function copy(text)
{
var copyText = document.getElementById(text).textContent;
document.querySelector('#aux').innerHTML+=('<input id="a" value='+copyText+'>')
document.getElementById("a").select();
document.execCommand("copy");
document.querySelector('#aux').innerHTML="";
//console.log(document.getElementById('text'));
}
<html>
<head>
</head>
<body>
<span id="aaa">hello</span>
<button onclick="copy('aaa')">copy</button>
<span id="aux"></span>
</body>
</html>
关于javascript - 如何从具有 id 的元素发送文本以在单击时起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54576372/