单击按钮时,将文本区域的文本复制到剪贴板中 [英] Copying text of textarea in clipboard when button is clicked

查看:93
本文介绍了单击按钮时,将文本区域的文本复制到剪贴板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个jQuery(或javascript)button,它选择textarea中的所有内容,然后在单击按钮时将文本复制到clipboard中.

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.

我发现了一些使用焦点事件的例子.但我正在寻找一个实际上必须单击以进行选择和复制的按钮.

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.

我该怎么做?

推荐答案

您需要使用 select() 选择textarea的文本并使用 execCommand('copy') 处理选定的文本.它可以在较高版本的浏览器中工作.

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.

$("button").click(function(){
    $("textarea").select();
    document.execCommand('copy');
});

另外,您也可以在没有jquery的情况下完成这项工作,如底部所示

Also you can do this work without jquery as shown in bottom

document.querySelector("button").onclick = function(){
  document.querySelector("textarea").select();
  document.execCommand('copy');
};

<button>Select</button>
<br/>
<textarea></textarea>

这篇关于单击按钮时,将文本区域的文本复制到剪贴板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆