点击复制功能 封装

问题:

clipboardJS插件ios系统下页面复制失败问题

需要将点击目标的节点设置为 : 

<textArea></textArea>
才能复制成功

解决办法:
自己实现点击复制封装

//定义函数
window.Clipboard = (function(window, document, navigator) {
  var textArea,
      copy;

  // 判断是不是ios端
  function isOS() {
    return navigator.userAgent.match(/ipad|iphone/i);
  }
  //创建文本元素
  function createTextArea(text) {
    textArea = document.createElement('textArea');
    textArea.innerHTML = text;
    textArea.value = text;
    document.body.appendChild(textArea);
  }
  //选择内容
  function selectText() {
    var range,
        selection;

    if (isOS()) {
      range = document.createRange();//创建区间
      range.selectNodeContents(textArea);//选择textArea区间内的所有内容
      selection = window.getSelection();//获取被选择文本的内容或者范围
      selection.removeAllRanges();//清除掉被选择的文本,初始化
      selection.addRange(range);//将被选择的文本替换成为指定文本
      textArea.setSelectionRange(0, -1);//0  -1为全选  
    } else {
      textArea.select();
    }
  }

//复制到剪贴板         ,复制之后的操作
  function copyToClipboard() {        
    try{
      if(document.execCommand("Copy")){
        alert("复制成功!");  
      }else{
        alert("复制失败!请手动复制!");
      }
    }catch(err){
      alert("复制错误!请手动复制!")
    }
    document.body.removeChild(textArea);
  }

  copy = function(text) {
    createTextArea(text);
    selectText();
    copyToClipboard();
  };

  return {
    copy: copy
  };
})(window, document, navigator);    
            
//使用函数调用      点击'.click-copy'节点后  ,,复制".weixin"节点的文本到粘贴板
$(".click-copy").on("click",function(){
  var  val = $(".weixin").text();
  Clipboard.copy(val);
});    

方案2:

const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

// 事例
copyToClipboard('Lorem ipsum'); 
// 'Lorem ipsum' copied to clipboard
原文地址:https://www.cnblogs.com/wxyblog/p/12247972.html