如何在网站上实现复制到剪贴板

2025-06-04

如何在网站上实现复制到剪贴板

在本文中,我们将了解如何在我们的网站上实现“复制到剪贴板”功能。点击Copy按钮后,段落标签的内容/文本将被复制到剪贴板,我们可以将其粘贴到系统中的任何位置。

让我们直接进入代码部分。

我假设您对 HTML、JavaScript 和 DOM 操作有一些基本的了解。

👨‍💻代码

我们将编写一个非常简单的 HTML 代码来显示段落内容和复制按钮。

index.html



<!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 align="center">
    <p id="content">The text to be copied.</p>
    <button id="copy">Copy Text</button>
    <script src="./script.js"></script>
</body>

</html>


Enter fullscreen mode Exit fullscreen mode

script.js



// Reference of the paragraph tag
const content = document.getElementById("content");

// Reference of the copy button
const copyBtn = document.getElementById("copy");

// Copy button's onclick handler
copyBtn.onclick = copyToClipboard;

// Method responsible for copying the content
function copyToClipboard() {
    navigator.clipboard
        .writeText(content.innerText)
        .then(() => alert("Copied to clipboard"))
        .catch((e) => alert(e.message));
}


Enter fullscreen mode Exit fullscreen mode

paragraph因此,我们首先获取标签和按钮的引用copy,然后将onclick处理程序分配给copy按钮。

单击copy按钮时,该copyToClipboard方法将被调用。

复制到剪贴板

在该copyToClipboard方法中我们使用剪贴板 API。

剪贴板 API 可用于在 Web 应用程序中实现剪切、复制和粘贴功能。

  • 系统剪贴板通过全局属性公开navigator.clipboard

  • 剪贴板对象的方法writeText期望一个字符串值作为参数,该参数将被写入剪贴板。

  • 它返回一个承诺,一旦剪贴板的内容更新,该承诺就会被解决。如果发生任何类型的错误,该承诺就会被拒绝。



...
navigator.clipboard
    .writeText(content.innerText)
    .then(() => alert("Copied to clipboard"))
    .catch((e) => alert(e.message));
...


Enter fullscreen mode Exit fullscreen mode

因此,我们将段落inner text标签传递给writeText方法,如果承诺得到解决,即文本已被复制。

✨ 奖金

类似地,我们可以实现cut功能。

将文本复制到剪贴板后,只需用空字符串覆盖段落标签的内部文本。



navigator.clipboard
.writeText(content.innerText)
.then(() => {
// Overwriting with an empty string
content.innerText = "";
alert("Copied to clipboard");
})
.catch((e) => alert(e.message));

Enter fullscreen mode Exit fullscreen mode




🔗 演示

GitHub 仓库:链接

尝试一下:链接


最初发表于blog.bibekkakati.me


感谢您的阅读🙏

如果您喜欢这篇文章或觉得它有帮助,请点赞👍

欢迎随时联系👋

Twitter | Instagram | LinkedIn


如果你喜欢我的作品并想支持它,可以在这里留言。我会非常感激。



文章来源:https://dev.to/bibekkakati/how-to-implement-copy-to-clipboard-on-a-website-1p0l
PREV
如何使用 Web Worker
NEXT
在浏览器中生成 HTML 元素的 PDF