繁体   English   中英

单击按钮时复制剪贴板中 textarea 的文本

[英]Copying text of textarea in clipboard when button is clicked

我正在寻找创建一个 jQuery(或 javascript) button ,该button选择textarea所有内容,然后在您单击按钮时将文本复制到clipboard

我找到了一些使用焦点事件的例子。 但我正在寻找一个按钮,您实际上必须单击该按钮才能进行选择和复制。

我怎样才能完成这项工作?

您需要使用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>

可以在不使用 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 元素由于某种原因被禁用时,或者如果您不想选择文本的视觉效果,那么下面的解决方案适合您。

$("#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');
      });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM