JS 用巧妙的方式实现复制内容到剪贴板
利用隐藏的 textarea 实现
js
export function copyToClipboard(text) {
let textArea = document.createElement("textarea");
textArea.style.position = "fixed";
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.width = "0";
textArea.style.height = "0";
textArea.style.padding = "0";
textArea.style.border = "none";
textArea.style.outline = "none";
textArea.style.boxShadow = "none";
textArea.style.background = "transparent";
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
let successful = document.execCommand("copy");
let msg = successful ? "成功复制到剪贴板" : "该浏览器不支持点击复制到剪贴板";
alert(msg);
} catch (err) {
alert("该浏览器不支持点击复制到剪贴板");
}
document.body.removeChild(textArea);
}