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

标签 javascript jquery html

<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/

相关文章:

javascript - Chrome/webkit中原生javascript解压功能

javascript - Protractor-如何在多个浏览器上开始测试,然后仅继续其中一个浏览器

javascript - 无法使 AJAX 调用或 session 正常运行

jquery - jQuery ajax 成功回调后,CSS 可见性属性在 Webkit 浏览器上不起作用

javascript - 如何在开始更改屏幕方向之前检测实际位置?

javascript - Canvas 添加事件监听器点击图片

javascript - Ngresource指定不同的URL的get all和get one

c# - ASP.NET JQuery AJAX POST 返回数据,但在 401 响应内

javascript - 无法通过 jquery 附加 HTML 文件

javascript - 如何运行 Mike Bostock 的 D3 示例?