gpt4 book ai didi

javascript - 如何在 html/javascript 中创建 "copy to clipboard"按钮

转载 作者:太空狗 更新时间:2023-10-29 13:33:56 26 4
gpt4 key购买 nike

<html>
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></p>

<script>
function GetValue()
{
var myarray= new Array("item1","item2","item3");
var random = myarray[Math.floor(Math.random() * myarray.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}
</script>

</html>

这是代码,当我生成一个随机单词让我们说“item1”显示时,我如何在它下面添加一个按钮,当我点击它时复制“item1”

最佳答案

我已经在你的代码中添加了一些行,试试吧!

<html>
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></p><br>
<button onclick="copyToClipboard('message')">Copy</button>

<script>
function GetValue()
{
var myarray= new Array("item1","item2","item3");
var random = myarray[Math.floor(Math.random() * myarray.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}

function copyToClipboard(elementId) {


var aux = document.createElement("input");
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");

document.body.removeChild(aux);

}
</script>

</html>

关于javascript - 如何在 html/javascript 中创建 "copy to clipboard"按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36233134/

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