纯JS将文本写入粘贴板

export const copyText = (text) => {
    let textarea = document.createElement("textarea");
    let currentFocus = document.activeElement;
    document.body.appendChild(textarea);
    textarea.value = text;
    textarea.focus();
    if (textarea.setSelectionRange) {
        textarea.setSelectionRange(0, textarea.value.length);
    } else {
        textarea.select();
    }
    let flag = false
    try {
        flag = document.execCommand("copy");
    } catch (e) {
        console.log(e);
    }
    document.body.removeChild(textarea);
    currentFocus.focus();
    return flag;
};

Done.

你可能感兴趣的:(纯JS将文本写入粘贴板)