我的博客
欢迎来到我的博客
bunny.icu

将文本复制到剪切板

将文本复制到剪切板

以下代码参考https://blog.csdn.net/lu090801/article/details/86520828
并将input的位置移动到了屏幕中间,以防止聚焦时页面抖动。
返回值表示是否复制成功。

function copyText(text) {
    let flag = false;
    let textarea = document.createElement("input");
    textarea.style.position = 'fixed';
    textarea.style.top = (document.documentElement.clientWidth / 2) + "px";
    textarea.style.left = (document.documentElement.clientHeight / 2) + "px";
    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();
    try {
        flag = document.execCommand("copy");
    } catch (eo) {}
    document.body.removeChild(textarea);
    currentFocus.focus();
    return flag;
}

版权声明


本作品系原创, 转载须遵循 CC BY-NC-ND 4.0 许可协议
本文标题:将文本复制到剪切板
本文链接:https://www.bunny.icu/archives/1127

推荐文章

发表评论

textsms
account_circle
email

bunny.icu

将文本复制到剪切板
将文本复制到剪切板
扫描二维码继续阅读
2020-11-11