Javascript 单击按钮时复制剪贴板中 textarea 的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37658524/
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
Copying text of textarea in clipboard when button is clicked
提问by GRU119
I'm looking to create a jQuery (or javascript) button
that selects everything in a textarea
and then copies the text to your clipboard
when you clicked on button.
我正在寻找创建一个 jQuery(或 javascript)button
,它选择 a 中的所有内容textarea
,然后clipboard
在您单击按钮时将文本复制到您的。
I have found some examples using the focus event. But I'm looking for a button that you actually have to click for the select and copy.
我找到了一些使用焦点事件的例子。但我正在寻找一个按钮,您实际上必须单击该按钮才能进行选择和复制。
How can i do this work?
我怎样才能完成这项工作?
回答by Mohammad
You need to use select()
to selecting text of textarea
and use execCommand('copy')
to coping selected text. Its work in upper version of browsers.
您需要使用select()
来选择文本textarea
并使用execCommand('copy')
来处理选定的文本。它在高版本浏览器中工作。
$("button").click(function(){
$("textarea").select();
document.execCommand('copy');
});
Also you can do this work without jqueryas shown in bottom
您也可以在没有 jquery 的情况下完成这项工作,如底部所示
document.querySelector("button").onclick = function(){
document.querySelector("textarea").select();
document.execCommand('copy');
}
document.querySelector("button").onclick = function(){
document.querySelector("textarea").select();
document.execCommand('copy');
};
<button>Select</button>
<br/>
<textarea></textarea>
回答by karoluS
It is possible to make this without using jQuery.
可以在不使用 jQuery 的情况下做到这一点。
Here's a pure js solution.
这是一个纯js解决方案。
function copy() {
let textarea = document.getElementById("textarea");
textarea.select();
document.execCommand("copy");
}
<textarea id="textarea"></textarea>
<br>
<button onclick="copy()">Copy</button>