document.execCommand文字剪贴

    !function() {
        // 创建影藏文本域
        var textarea = document.createElement('textarea');
        textarea.id = 'text';
        textarea.value = new Date();
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        
        // 根据ua分别绑定ios和android事件
        if ((/iPhone/ig).test(navigator.userAgent)) {
            var btns = document.getElementsByTagName('div');
            for (var i=0;i<btns.length;i++) {
                btns[i].onclick = function() {
                    copyText();
                }
            }
        }else {
            document.body.addEventListener('touchmove',copyText);
            document.body.addEventListener('click',copyText);
        }
        
        // 文本拷贝到系统剪贴板
        function copyText() {
            document.getElementById("text").select();
            document.execCommand("SelectAll");
            document.execCommand("copy");
            try {
                var succeeded = document.execCommand("copy");
                console.log(succeeded);
            }catch(err){
                console.log(err);
            }
        }
    }();

  

posted @ 2017-11-07 16:13  鱿鱼须须  阅读(271)  评论(0编辑  收藏  举报