js 复制文本到粘贴板

//html
在iOS Safari中,剪贴板API有一些限制(实际上是安全措施):
 
于安全原因,iOS Safari只允许容器中的document.execCommand('copy')文本contentEditable。
 
解决方法是检测iOS Safari,并contentEditable在执行之前快速切换document.execCommand('copy')。
 
 
它copy仅在有效的选择上触发事件,cut并且paste仅在专注的可编辑字段中触发事件。
 
它只支持操作系统剪贴板读/写通过快捷键,而不是通过document.execCommand()。
<div id="bar" contentEditable="false">文本文本</div>
<button id="copybtn" class="copycode">点击复制</button>
$('#copybtn').click(function () {

       var el = document.querySelector('#bar');
       var range = document.createRange();
       range.selectNodeContents(el);

       var selection = window.getSelection();
       selection.removeAllRanges();
       selection.addRange(range);

       document.execCommand('copy');
        alert("复制成功")
   });

   function get_ios8() {
        // 判断是否 iPhone 或者 iPod
       if ((navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i))) {
            // 判断系统版本号是否大于3小于8
           var version8 = Boolean(navigator.userAgent.match(/OS [3-8]_\d[_\d]* like Mac OS X/i));
            if (version8) {
               $('#copybtn').remove();
            }
       } else {
            return false;
       }
    }
  get_ios8();
ios8以下的系统,依然不支持 document.execCommand('copy');
 
安卓系统下没问题;
posted on 2018-01-04 21:49  小碎步  阅读(869)  评论(0编辑  收藏  举报