编辑截止2016年
截至2016年,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都能够使用document.execCommand(“复制”)以编程方式将所选文本复制到剪贴板。
与浏览器中的其他一些操作(如打开一个新窗口)一样,复制到剪贴板只能通过特定的用户操作(如鼠标单击)来完成。例如,它不能通过计时器来完成。
下面是一个代码示例:
document.getElementById("copyButton").addEventListener("click", function() {
copyToClipboard(document.getElementById("copyTarget"));
});
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;
}
input {
width: 400px;
}
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">
这里有一个更高级的演示:https://jsfiddle.net/jfriend00/v9g1x0o6/
你也可以用clipboard.js获得一个预构建的库来做这个。
古老的,历史的答案
由于安全原因,任何现代浏览器都不允许通过JavaScript直接复制到剪贴板。最常见的解决方法是使用Flash功能复制到剪贴板,这只能由用户直接单击触发。
如前所述,ZeroClipboard是一组用于管理Flash对象以执行复制的流行代码。我用过。如果Flash安装在浏览设备上(排除了手机或平板电脑),它就能正常工作。
下一个最常见的解决方法是将剪贴板绑定的文本放入一个输入字段,将焦点移到该字段,并建议用户按Ctrl + C复制文本。
关于这个问题的其他讨论和可能的解决方法可以在这些之前的Stack Overflow帖子中找到:
我如何复制到剪贴板在JavaScript?
如何使用jQuery将文本复制到客户端的剪贴板?
如何复制到剪贴板没有Flash?
这些问题询问了使用Flash的现代替代方案,得到了大量的赞,但没有答案(可能是因为根本不存在):
HTML5替代基于flash的ZeroClipboard安全复制数据到剪贴板?
复制到剪贴板没有Flash
Internet Explorer和Firefox曾经使用非标准api来访问剪贴板,但它们的最新版本已经弃用了这些方法(可能是出于安全原因)。
有一种新兴的标准试图提出一种“安全”的方法来解决最常见的剪贴板问题(可能需要特定的用户操作,就像Flash解决方案所要求的那样),看起来它可能会在最新版本的Firefox和Chrome中部分实现,但我还没有证实这一点。