JavaScript 实现将 Input 或 Textarea 内容复制到剪贴板
作者:闭包旅人时间:2026-10-30 05:07:06浏览:100
本文介绍如何在 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 实现复制内容到剪贴板的完整代码示例,希望能为相关开发工作提供帮助。
作者最新文章
什么时候该用JS构造器:与工厂模式、字面量的选择对比
2026-11-05 16:18:22
推荐几款轻量级JS照片墙开源库及对比
2026-11-05 15:56:19
JavaScript递归写法有哪些常见陷阱及避免方法
2026-11-05 14:53:38
JS数组浅拷贝与深拷贝怎么选?场景与方法总结
2026-11-05 14:41:02
p5.js 中 setup() 和 draw() 函数的执行机制详解
2026-11-05 12:32:38
