js 复制文字和图片到剪贴板

js 复制文字和图片到剪贴板

最近有个需求,要同时复制多张图片和文字到剪贴板,网上找了好多方法,都不行,最后上个厕所,想到直接翻w3c文档,终于实现了。让大家不迷路,共享出来,不用谢,点赞就行。

不多说,上代码

function 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 += `${sets.txts}`
        }else{
            sets.txts.forEach(item=>{
                child += `${item}`
            });
        }
    }
    if(sets.imgs){
        if(typeof sets.imgs === 'string'){
            sets.imgs = sets.imgs.indexOf('https')>-1?sets.imgs.replace('https','http'):sets.imgs;
            child += `${sets.imgs}" />`
        }else{
            sets.imgs.forEach(item=>{
                item = item.indexOf('https')>-1?item.replace('https','http'):item;
                child += `${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);
    } else if (document.body.createTextRange) {//ie
        let range = document.body.createTextRange();
        range.moveToElementText(dom);
        range.select();
    }
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    imgDiv.parentNode.removeChild(imgDiv);
}

那么怎么使用呢

copyInfo({
   txts: '请复制我',
   imgs: ['https://img.shop.wusehaowu.com/20210407/da46894987254688af008a95ad121da9.png','https://t00img.yangkeduo.com/goods/images/2021-02-27/1e5bc93f957fefabc13d994a9f379dda.jpeg']
});

你可能感兴趣的:(功能性代码,javascript)