【发布时间】:2016-10-06 03:01:20
【问题描述】:
我正在寻找创建一个 jQuery(或 javascript)button,它选择 textarea 中的所有内容,然后在您单击按钮时将文本复制到您的 clipboard。
我发现了一些使用焦点事件的例子。但我正在寻找一个您实际上必须单击以进行选择和复制的按钮。
我该怎么做?
【问题讨论】:
标签: javascript jquery copy textarea
我正在寻找创建一个 jQuery(或 javascript)button,它选择 textarea 中的所有内容,然后在您单击按钮时将文本复制到您的 clipboard。
我发现了一些使用焦点事件的例子。但我正在寻找一个您实际上必须单击以进行选择和复制的按钮。
我该怎么做?
【问题讨论】:
标签: javascript jquery copy textarea
您需要使用select() 来选择textarea 的文本,并使用execCommand('copy') 来应对选定的文本。它在高版本浏览器中工作。
$("button").click(function(){
$("textarea").select();
document.execCommand('copy');
});
您也可以不使用 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>
【讨论】:
textarea 元素被标记为disabled 上面将不起作用,因此您需要事先删除 disabled 属性。
不使用 jQuery 也可以做到这一点。
这里是纯js解决方案。
function copy() {
let textarea = document.getElementById("textarea");
textarea.select();
document.execCommand("copy");
}
<textarea id="textarea"></textarea>
<br>
<button onclick="copy()">Copy</button>
【讨论】:
textarea.setSelectedRange(0,99999) (w3schools.com/howto/howto_js_copy_clipboard.asp),它就不起作用。
当您的 textarea 元素由于某种原因被禁用时,或者如果您不想看到所选文本的视觉效果,那么下面的解决方案适合您。
$("#button_id").click(function(){
var $temp = $("<textarea></textarea>");
$("body").append($temp);
$temp.val($("#textarea_source").val()).select(); <-- #textarea_source: id of textarea source to be copied to the clipboard
document.execCommand("copy");
$temp.remove();
})
【讨论】:
**Copying text of textarea**
<textarea id="text" class="form-control" rows="21" cols="40" name="text">
This word has two main meanings. The first has to do with being pleased and satisfied (feeling content) or making someone else feel happy and at peace with things (contenting them). The other meaning has to do with subject matter: the content of a history class might be American history. The content of a math class might be geometry. As long as there's a topic or subject, there's content.
</textarea>
**The following code added to script area**
$("button").click(function(){
$("textarea").select();
document.execCommand('copy');
});
【讨论】: