如何使用 Javascript 将文本复制到剪贴板

2025-06-07

如何使用 Javascript 将文本复制到剪贴板

将数据从浏览器复制到剪贴板虽然功能不多,但却非常强大。无需手动选择,crtl + c在阅读较长的编码文章时确实节省了一些时间。为了方便读者,我刚刚在所有代码片段旁边添加了一个小的剪贴板标志。继续阅读,了解我是如何做到的。

样板


创建一个index.html文件,并main.js在你选择的目录中创建一个文件。在 index.file 中填写以下内容,然后我们开始吧。



<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Copy to clipboard</title>
  </head>
  <body>
    <h1>With textarea</h1>
    <section>
      <textarea
        placeholder="Write your content here and press 'Copy Text'"
        id="clipboard-area"
        cols="30"
        rows="2"
      ></textarea>
      <textarea
        placeholder="Paste your content here"
        cols="30"
        rows="2"
      ></textarea>
    </section>
    <button style="width: 260px" onclick="handleCopyTextFromArea()">
      Copy text
    </button>

    <h1>Without textarea</h1>
    <section style="display: flex">
      <p style="width: 260px; margin: 0">
        Lorem ipsum, dolor sit amet consectetur adipisicing elit.
      </p>
      <textarea
        placeholder="Paste your content here"
        cols="30"
        rows="2"
      ></textarea>
    </section>
    <button style="width: 260px" onclick="handleCopyTextFromParagraph()">
      Copy text
    </button>

    <script src="main.js"></script>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

我们将为按钮附加两个功能 -handleCopyTextFromArea并且

handleCopyTextFromParagraph- 让我们赋予它们生命。

该图像显示了一个简单的 HTML 用户界面,其中包含三个文本区域和一个段落

方法 1: execCommand('copy')

虽然根据 MDN 文档,此方法的功能已被弃用,但它仍然可以与textarea-html 标签配合使用。即使您没有这样的标签,也可以非常快速地创建它,并用所需的文本内容填充其值。

如果有可用的文本区域,请将以下内容添加到您的index.html



function handleCopyTextFromArea() {
  const area = document.querySelector('#clipboard-area')
  area.select();
  document.execCommand('copy')
}


Enter fullscreen mode Exit fullscreen mode

如果您没有上述元素,只需在复制时添加即可。以下步骤通常非常轻松,用户不会注意到额外的标签被添加和删除:

  1. 创建textarea元素并将其添加到DOM
  2. 使用段落中的文本或任何其他元素填充其值。
  3. 使用上述execCommand('copy')方法复制文本内容
  4. 再次移除元素。


function handleCopyTextFromParagraph() {
  const body = document.querySelector('body');
  const paragraph = document.querySelector('p');
  const area = document.createElement('textarea');
  body.appendChild(area);

  area.value = paragraph.innerText;
  area.select();
  document.execCommand('copy');

  body.removeChild(area);
}


Enter fullscreen mode Exit fullscreen mode

现在,如果您尝试crtl + v将文本粘贴到右侧的文本区域,您应该会看到输入被粘贴了。虽然这种方法仍然非常有效,但现代浏览器已经实现了自己的接口来处理剪贴板功能。接下来我们来看一下。

方法 2:剪贴板 API

剪贴板 API 是一种基于 Promise 的现代方法,它专注于剪贴板,而不是同时执行多项操作。它会请求您的许可,并且仅通过 https 工作,这使其在设计上更加安全。根据Can I use 的说法,旧版浏览器不支持此功能,因此您可能也需要考虑使用其他替代方案。

让我们handleCopyTextFromParagraph用下面的函数替换上面的函数:



function handleCopyTextFromParagraph() {
  const cb = navigator.clipboard;
  const paragraph = document.querySelector('p');
  cb.writeText(paragraph.innerText).then(() => alert('Text copied'));
}


Enter fullscreen mode Exit fullscreen mode

真的就是这样。你可能想.then()用一些更简洁的用户反馈来替换回调,并检查用户权限,这样一来,目标就达成了,文本已经可用,可以解析了。

更新:使用 Vue 3 指令复制到剪贴板

如果您使用 Vue.js 构建应用程序,则可以使用 Vue 自定义指令包装上述函数。然后,通过点击(或以任何其他方式与)绑定了 v-clip 的组件来实现相同的功能。

在 main.js 文件中声明以下函数,并在创建 Vue 应用程序后将其全局注册:



const vClip = {
  // For Vue 2, you can use bind instead of mounted
  mounted: (el) => {
    el.addEventListener('click', () => {
      const cb = navigator.clipboard;

      // Check if the clicked on element is an input element
      const input = el.tagName === 'input' ? 
          el : 
          el.querySelector('input');

      // Copy the text to clipboard
      cb.writeText(input.value).then(() => alert('Text copied'));
    });
  },
};

// Create the app and mount it
const app = createApp(App);

app.directive('clip', vClip);
app.mount('#app');


Enter fullscreen mode Exit fullscreen mode

然后,假设您有以下组件:



<q-base-input
 label="Short link:"
 v-model="form.result"
 disabled />


Enter fullscreen mode Exit fullscreen mode

您可以v-clip向其中添加指令:



<q-base-input
 label="Short link:"
 v-clip
 v-model="form.result"
 disabled />


Enter fullscreen mode Exit fullscreen mode

这篇文章最初发布于https://blog.q-bit.me/use-javascript-to-copy-text-to-the-clipboard/
感谢您的阅读。如果您喜欢这篇文章,欢迎在 Twitter 上关注我们 🐤 @qbitme

文章来源:https://dev.to/tqbit/how-to-use-javascript-to-copy-text-to-the-clipboard-2hi2
PREV
一个面向初学者的带有 Styled-components 的 React 网站 ✨
NEXT
React 中的 TypeScript 简介