美文网首页
使用JS拷贝内容到剪切板

使用JS拷贝内容到剪切板

作者: RoyChina | 来源:发表于2019-05-24 14:17 被阅读0次
    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;
    

    相关文章

      网友评论

          本文标题:使用JS拷贝内容到剪切板

          本文链接:https://www.haomeiwen.com/subject/uxmgzqtx.html