如何在html / javascript中创建“复制到剪贴板”按钮

前端之家收集整理的这篇文章主要介绍了如何在html / javascript中创建“复制到剪贴板”按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<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","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>

猜你在找的HTML相关文章