详细介绍
参考 阮一峰的网络日志 剪贴板操作 Clipboard API 教程 https://www.ruanyifeng.com/blog/2021/01/clipboard-api.html
代码
1.对于图片是http地址且长度不是很长
const selection = window.getSelection();
if (selection.rangeCount > 0) selection.removeAllRanges();
const range = document.createRange();
range.selectNode(this.$refs.foo); //传入dom
selection.addRange(range);
let copy = document.execCommand("copy"); //copy是复制
console.log("copy", copy); //打印获取的dom
this.$message({
type: "success",
message: "图片复制成功!",
duration: 1000,
});
selection.removeAllRanges(); //清除缓存
2.对于图片是base64的长字符图片
// 接口字段base64_img以 data:image/png;base64, 须剪掉
const pic = this.pic.slice(22);
const blobInput = this.convertBase64ToBlob(pic, "image/png");
const clipboardItemInput = new ClipboardItem({
"image/png": blobInput,
});
navigator.clipboard.write([clipboardItemInput]);