在h5中实现兼容性比较好的点击复制方法

155 阅读1分钟
h5中实现兼容性比较好的点击复制方法,代码如下
   function copy(text){
       function selectText(textbox,startIndex,stopIndex){
           if(textbox.createTextRange){
               const range=textbox.createTextRange();
               range.moveStart('character',startIndex);
               range.moveEnd('character',startIndex-stopIndex);
               range.select();
           }else{
               textbox.setSelectionRange(startIndex,stopIndex);
               textbox.focus();
           }
       }
   
      return new Promise((resolve,reject)=>{
          let textArea=document.createElement('textarea');
          textArea.style.position='fixed';
          textArea.style.top='-10000';// 把生成的输入框移动到视线之外
          textArea.style.zIndex='-1';// 把生成的输入框移动到视线之外
          textArea.readOnly='readOnly';// 设置为只读,这样在移动端才不会弹出虚拟键盘
          textArea.value= text;
          document.body.appendChild(textArea);
          selectText(textArea,0,text.length)
          try{
              if(document.execCommand('copy')){
                  document.execCommand('copy')
                  resolve();
              }else{
                reject('当前浏览器不支持该复制方法');
              }
          } catch(error){
                reject(error)
          }
          textArea.blur();//去掉选中,因为的移动端ios 上,会出现点了选择左上角出现点问题
          document.body.removeChild(textArea);
      })
   }
   
   //使用
   copy('张三').then(res=>{console.log('复制成功')}).catch(()=>{console.log('复制失败')})