无需插件!让JS帮你实现跨浏览器的内容复制到剪贴板
最编程
2024-02-15 08:36:56
...
HTML部分:
<button onclick="copyToClip('内容')"> Copy </button>
JS部分:
/**
* 复制单行内容到粘贴板
* content : 需要复制的内容
* message : 复制完后的提示,不传则默认提示"复制成功"
*/
function copyToClip(content, message) {
var aux = document.createElement("input");
aux.setAttribute("value", content);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);
if (message == null) {
alert("复制成功");
} else{
alert(message);
}
}
【补充】
如果你想复制多行数据的话,可以采用如下方法。
/**
* 复制多行内容到粘贴板
* contentArray: 需要复制的内容(传一个字符串数组)
* message : 复制完后的提示,不传则默认提示"复制成功"
*/
function copyToClip(contentArray, message) {
var contents = "";
for (var i = 0; i < contentArray.length; i++) {
contents += contentArray[i] + "\n";
}
const textarea = document.createElement('textarea');
textarea.value = contents;
document.body.appendChild(textarea);
textarea.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
}
document.body.removeChild(textarea);
if (message == null) {
alert("复制成功");
} else{
alert(message);
}
}
下一篇: 跨浏览器剪贴板复制功能实现 - 修正版