JavaScript 实现将 Input 或 Textarea 内容复制到剪贴板

作者:闭包旅人

时间:2026-10-30

浏览:99

本文介绍如何在 JavaScript 项目中通过按钮点击,将 Input 或 Textarea 元素的选中值直接复制到系统剪贴板。提供了完整的 copyToClipboard 函数实现逻辑及调用示例,适用于需要快速集成复制功能的前端开发场景。

文章目录

JavaScript 复制内容到剪贴板实现

近期在前端开发中遇到一个常见需求:用户点击按钮后,需将 Input 或 Textarea 中的文本内容直接复制到系统剪贴板。以下分享具体的实现思路与代码,开发者可直接将该功能集成至现有项目中。

具体实现代码如下:


function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}

调用方式如下所示:


copyToClipboard(document.getElementById("name"));

执行后,ID 为 name 的元素内容即被成功写入剪贴板。

以上即为 JavaScript 实现复制内容到剪贴板的完整代码示例,希望能为相关开发工作提供帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章