原生js实现将图片内容复制到剪贴板

 原生js实现将图片内容复制到剪贴板_第1张图片


核心代码

/*复制图片*/
copyImg(dom) {
    /* 警告:dom不能是img标签,建议用DIV标签包裹img标签,否者会报错!不支持复制背景图! */
    dom.style.userSelect = 'auto';
    let selection = getSelection(), range = document.createRange();
    selection.removeAllRanges(), range.selectNodeContents(dom), selection.addRange
(range), document.execCommand('copy'), selection.removeAllRanges();
},

用例


    
 

扩展用法(自定义复制成功提示文本+弹窗方式)

/*复制图片*/
copyImg(dom, isAlert, successMsg = '') {
    /* 警告:dom不能是img标签,建议用DIV标签包裹img标签,否者会报错!不支持复制背景图! */
    dom.style.userSelect = 'auto';
    let selection = getSelection(), range = document.createRange();
    selection.removeAllRanges(), range.selectNodeContents(dom), selection.addRange
        (range), document.execCommand('copy'), selection.removeAllRanges();
    if (isAlert) {
        if (typeof isAlert === "function") {
            isAlert(successMsg || "图片复制成功");
        } else {
            Message.success(successMsg || "图片复制成功");
        }
    }
},

你可能感兴趣的:(Vue.js,javascript,前端,html)