js原生代码复制

function copy (attrs) {
    let target = null;
    re = new RegExp("<br>","g");
    var attr = attrs.replace(re,"");
    if (attr) {
        target = document.createElement('div');
        target.id = 'tempTarget';
        target.style.opacity = '0';
        target.innerText = attr;
        document.body.appendChild(target);
    }
    try {
        let range = document.createRange();
        range.selectNode(target);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
        // 已复制
    } catch (e) {
        // 复制失败,请手动复制
    }
    if (attr) {
        target.parentElement.removeChild(target);
    }
    return false;
}

猜你喜欢

转载自blog.csdn.net/qq_15957557/article/details/102406546