欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用JS拷贝内容到剪切板

程序员文章站 2022-06-16 10:49:14
...
JS拷贝内容到剪切板(2019/5/29更新兼容所有浏览器)
const copyTextToClipboard = input => {
    if (!input) return false;
    const element = document.createElement("textarea");

    element.value = input;

    // Prevent keyboard from showing on mobile
    element.setAttribute("readonly", "");

    element.style.contain = "strict";
    element.style.position = "absolute";
    element.style.left = "-9999px";
    element.style.fontSize = "12pt"; // Prevent zooming on iOS

    const selection = document.getSelection();
    let originalRange = false;
    if (selection.rangeCount > 0) {
        originalRange = selection.getRangeAt(0);
    }

    document.body.appendChild(element);
    element.select();

    // Explicit selection workaround for iOS
    element.selectionStart = 0;
    element.selectionEnd = input.length;

    let isSuccess = false;
    isSuccess = document.execCommand("copy");

    element.parentNode.removeChild(element);

    if (originalRange) {
        selection.removeAllRanges();
        selection.addRange(originalRange);
    }

    return isSuccess;
};

module.exports = copyTextToClipboard;
module.exports.default = copyTextToClipboard;