簡體   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