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

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

问题描述

我正在寻找创建一个 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');
}

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

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

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

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