本文内容如下:
- 使用 clipboard.js 插件
- 使用 document.execCommand() 原生方法
- 复制图片
1.使用 clipboard.js 插件
该插件使用比较简单,兼容性较好。具体使用方法见:github clipboard.js
兼容性:
2.使用 document.execCommand() 原生方法
直接看代码:
/**
* 复制内容
* @param {String} value 需要复制的内容
* @param {String} type 元素类型 input, textarea
*/
export function copyContent(value, type = 'input') {
const input = document.createElement(type);
input.setAttribute('readonly', 'readonly'); // 设置为只读, 防止在 ios 下拉起键盘
// input.setAttribute('value', value); // textarea 不能用此方式赋值, 否则无法复制内容
input.value = value;
document.body.appendChild(input);
input.setSelectionRange(0, 9999); // 防止 ios 下没有全选内容而无法复制
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
这里主要解决了 ios 下的 bug,以及使用 textarea 来解决换行内容的复制。
兼容性:
3.复制图片(移动端可能达不到想要的效果)
复制一张图片
/**
* 复制网络图片
*/
export function copyImg(imgUrl: string) {
fetch(imgUrl)
.then(res => res.blob())
.then(blob => {
toDataURL(blob).then(base64 => {
navigator.clipboard.write([new ClipboardItem({ 'image/png': dataURLToBlob(base64, 'image/png') })])
})
})
}
复制多张图片
/**
* 复制文字或图片
* (通过创建元素并选中的方式实现复制)
*/
export function copyInfo(sets: { txts?: string | string[]; imgs?: string | string[]; callback?: () => void }) {
let imgDiv = document.createElement('div')
imgDiv.id = '__imgDiv'
imgDiv.setAttribute('style', 'z-index: -1;position: fixed;')
let child = ''
if (sets.txts) {
if (typeof sets.txts === 'string') {
child += `<span>${sets.txts}</span>`
} else {
sets.txts.forEach(item => {
child += `<span>${item}</span>`
})
}
}
if (sets.imgs) {
if (typeof sets.imgs === 'string') {
sets.imgs = sets.imgs.indexOf('https') > -1 ? sets.imgs.replace('https', 'http') : sets.imgs
child += `<img src="${sets.imgs}" />`
} else {
sets.imgs.forEach(item => {
item = item.indexOf('https') > -1 ? item.replace('https', 'http') : item
child += `<img src="${item}" />`
})
}
}
imgDiv.innerHTML = child
document.body.insertBefore(imgDiv, document.body.lastChild)
let dom = document.getElementById('__imgDiv')
// console.log(dom)
if (window.getSelection) {
// chrome等主流浏览器
let selection = window.getSelection()
let range = document.createRange()
range.selectNodeContents(dom!)
selection?.removeAllRanges()
selection?.addRange(range)
// @ts-ignore
} else if (document.body.createTextRange) {
// ie
// @ts-ignore
let range = document.body.createTextRange()
range.moveToElementText(dom)
range.select()
}
document.execCommand('copy')
window.getSelection()?.removeAllRanges()
imgDiv.parentNode?.removeChild(imgDiv)
}
// 使用
copyInfo({
imgs: [
'https://xxx.test.png',
'https://xxx.test.png'
]
})