JS复制文本,兼容各种浏览器

function copyText(txt: string) {
    return new Promise((resolve, reject) => {
        const domCopy = function () {
            const input = document.createElement('input');
            input.value = txt;
            input.style.position = "absolute";
            input.style.top = "-100px"
            document.body.appendChild(input)
            setTimeout(() => {
                input.select()
                let r = document.execCommand("copy");
                if (r) {
                    resolve("复制成功")
                } else {
                    reject("复制失败")
                }
                input.remove();
            }, 100)
        }
        if (navigator.clipboard) {
            navigator.clipboard.writeText(txt).then(resolve).catch(() => {
                domCopy()
            });
        } else {
            domCopy()
        }
    })

}

  

posted @ 2024-12-02 14:24  技术探索者  阅读(83)  评论(0)    收藏  举报