原生jscopy兼容ios和安卓

//author limenghui created in 2018.7.26

const JsCopy={
    //原生js複製內容到複製板
   makeCopy(txt){
        const input = document.createElement('input');
       //防止ios點擊複製時屏幕下方會出現白屏抖動,仔細看是拉起鍵盤又瞬間收起
        input.setAttribute('readonly', 'readonly');
        input.setAttribute('value',txt)
        document.body.appendChild(input);
        let sysMsg=this.getOs();
        console.log(sysMsg,'檢測版本信息')
       //input.select() 在ios下並沒有選中全部內容,使用以下來選中內容
           if(sysMsg == 'ios'){
               //ios複製
               let obj=this.iosCopy(txt);
               this.destoryNode(obj.html,obj.style)
               //input.setSelectionRange(0,input.value.length);  
           }else if(sysMsg == 'android'){
               //android選擇複製內容
               input.select(txt);    
           }
           document.execCommand('copy',true);
           document.body.removeChild(input);
              
    },
    //  兼容ios複製
   iosCopy(txt){
        let obj=this.render(txt);
      
        window.getSelection().removeAllRanges();//這段代碼必須放在前面否則無效
        let content = document.querySelector('.jsCopy');
        console.log(content)
       
        var range = document.createRange();
        // 選中需要複製的節點
        range.selectNode(content);
        // 執行選中元素
        window.getSelection().addRange(range);
        // 執行 copy 操作
        document.execCommand('copy');

        // 移除選中的元素
        window.getSelection().removeAllRanges();
        return obj;
    },
    //渲染成ios需要複製的節點並添加樣式
   render(txt){
        var html=document.createElement('div');
        html.className='jsCopy';
        html.innerText=txt;
        document.body.appendChild(html)
        var style=document.createElement('style');
        style.innerHTML='body{-webkit-user-select:text}.jsCopy{position:absolute;top:0;left:-200px;color:transparent;background:transparent}'
        document.head.appendChild(style)
        let nodeObj={
            "html":html,
            "style":style
        }
        return nodeObj;
    },
    //方法調用完畢後摧毀節點和多餘樣式
    destoryNode(html,style){
        document.body.removeChild(html);
        document.head.removeChild(style);
    },
    //獲取操作系統
    getOs(){
        let userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || '';
        if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent)) return 'ios'
        if (/android/i.test(userAgent)) return 'android'
    }
}
export default JsCopy;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章