前端js复制文本到剪切板方法(无需右键复制)

// 复制的方法
function copyText(text, callback) { // text: 要复制的内容, callback: 回调
    let tag = document.createElement('input');
    tag.setAttribute('id', 'cp_hgz_input');
    tag.value = text;
    document.getElementsByTagName('body')[0].appendChild(tag);
    document.getElementById('cp_hgz_input').select();
    document.execCommand('copy');
    document.getElementById('cp_hgz_input').remove();
    if (callback) {
        callback(text)
    }
}

调用该函数代码:

copyText('复制内容', function (text) {
    alert("复制["+text+"]成功!");
});
posted @ 2019-12-26 17:01  wxxwjef  阅读(877)  评论(0编辑  收藏  举报