这是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>
发布于 2018-07-28 07:13:14
它不能工作的原因是因为你不能对一个可变的.select()进行操作;所以当你复制一个document.execCommand(“复制”)时,你要复制任何其他选定的文本,试着把这些东西放到输入框中,然后再尝试.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>
https://stackoverflow.com/questions/51566502
复制相似问题