dandanyajin
今天更新博客了吗?
// 点击复制到剪贴板
  const copyToClipboard = (content)=> {
      if (window.clipboardData) {
          window.clipboardData.setData("text", content);
      } else {
          (function (content) {
              document.oncopy = function (e) {
                  e.clipboardData.setData("text", content);
                  e.preventDefault();
                  document.oncopy = null;
              };
          })(content);
          document.execCommand("Copy");
      }
  }

 

 // 点击复制到剪贴板    (兼容ios)
  const copyToClipboard = (content)=> {
    let oInput = document.createElement("input");
    oInput.value = content;
    document.body.appendChild(oInput);
    oInput.select(); // 选择oInput中所有文本对象
    if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//兼容ios
      if (!document.execCommand("Copy")) {
        oInput.setSelectionRange(0, oInput.value.length);
      }
    }
    document.execCommand("Copy"); // 执行浏览器复制命令
    document.body.removeChild(oInput);
    return new Promise((resolve,reject)=>{
        if (document.execCommand("Copy")) {
            resolve(content);
        }else{
            reject(content);
        }
    })
  }

 注释:setSelectionRange()方法是作用在input元素上的;这个方法可以为当前元素内的文本设置备选中范围;inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection);

posted on 2022-09-06 16:56  dandanyajin  阅读(994)  评论(0编辑  收藏  举报