如何在 html/javascript 中创建“复制到剪贴板”按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36233134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create "copy to clipboard" button in html/javascript
提问by ammartjr
<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>
this is the code and when i generate a random word lets say "item1" shows ,how can i add a button below it that when i click it copies the "item1"
这是代码,当我生成一个随机单词时,可以说“item1”显示,我如何在其下方添加一个按钮,当我单击它时会复制“item1”
回答by selem mn
I've added some lines to your code ,try this it works !
我在你的代码中添加了一些行,试试这个吧!
<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>
回答by bschlueter
You're looking for the script to be:
您正在寻找的脚本是:
function GetValue()
{
var myarray = new Array("item1", "item2", "item3");
var random = myarray[Math.floor(Math.random() * myarray.length)];
var message = document.getElementById("message");
message.value = random;
message.select();
document.execCommand('copy');
}
The message element needs to be a selectable element, i.e. a text input or textarea: <input id="message">
消息元素需要是可选元素,即文本输入或文本区域: <input id="message">