JavaScript的新手,我试图用一个按钮将代码中的一些文本复制到剪贴板。这似乎无效。.请让我知道我所缺少的。谢谢!
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Copy text</button>
<script>
function myFunction() {
var copyText = "myText";
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
</body>
</html>
答案 0 :(得分:2)
它不起作用的原因是因为您不能对变量.select();进行操作。因此,当您执行document.execCommand(“ copy”);时,您复制任何其他选定的文本 尝试将内容放入输入框中,然后尝试.select();
<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText"> </input>
<button onclick="myFunction()">Copy text</button>
<script>
function myFunction() {
var copyText = document.getElementById("myId");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
</body>
</html>
,如果要隐藏文本框,请执行
<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText" style="display:none;"> </input>
<button onclick="myFunction()">Copy text</button>
<script>
function myFunction() {
var copyText = document.getElementById("myId");
copyText.style = "display:inline";
copyText.select();
copyText.style = "display:none";
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
</body>
</html>