/* 复制文字或图片
使用:copyInfo({
txts: '请复制我',
imgs: ['https://profile.csdnimg.cn/D/0/B/2_qq812457115']
});
*/
export const copyInfo = (sets)=> {
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);
}
document.execCommand('copy');
window.getSelection().removeAllRanges();
imgDiv.parentNode.removeChild(imgDiv);
}
JS——复制文字或图片
于 2023-03-13 18:16:34 首次发布