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



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

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

我该如何完成这项工作?

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

现代解决方案

document.execCommand('copy')现已弃用

相反,我们现在有了剪贴板 API

可以使用 writeText() 属性来完成此操作:

$('button').on('click', () => {
  navigator.clipboard.writeText($('textarea').val()).then(
    () => {
      console.log('clipboard successfully set');
    },
    () => {
      console.error('clipboard write failed');
    }
  );
});

或者只是简单地:

$('button').on('click', () => {
  navigator.clipboard.writeText($('textarea').val());
});

奖励:这适用于禁用的文本区域并且跨浏览器兼容

当您的 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');
      });

最新更新