js复制文本功能实现,适用于Android和IOS

首先文本只有选中才可以复制,所以简单的做法就是创建一个隐藏的 input,然后绑定需要复制的文本。

另外如果将 input 设置为 `type="hidden" 或者 display:none 则无法选中文本,也就无法复制,可以设置 position:absolute;left:-999px; 来隐藏文本域。

  • 静态复制
const copyInput = document.querySelector('#copyInput');

copyInput.value = '需要复制的文本';
copyInput.select();
document.execCommand('Copy');
  • 动态创建 input
  let H5copyLink = () => {
        if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
          /**
           * ios中不能复制属性值,只能复制文本元素节点;
           * (解决方案:可以把文字颜色设成背景色就能达到隐藏看不见的效果不影响显示);
           */
          window.getSelection().removeAllRanges(); //这段代码必须放在前面否则无效
          var Url2 = document.getElementById("copy"); //要复制文字的节点
          var range = document.createRange();
          // 选中需要复制的节点
          range.selectNode(Url2);
          // 执行选中元素
          window.getSelection().addRange(range);
          // 执行 copy 操作
          var successful = document.execCommand("copy");
          // 移除选中的元素
          window.getSelection().removeAllRanges();
        } else {
          //创建input
          let inputZ = document.createElement("input");
          //添加Id,用于后续操作
          inputZ.setAttribute("id", "inputCopy");
          //获取当前链接
          inputZ.value = con;
          //创建的input添加到body
          document.body.appendChild(inputZ);
          //选中input中的值
          document.getElementById("inputCopy").select();
          //把值复制下来
          try {
            document.execCommand("Copy");
            uni.showToast({
              title: "复制成功",
              duration: 3000
            });
          } catch (err) {
            uni.showToast({
              title: "此设备暂不支持复制操作,您可以长按文本内容选择复制",
              duration: 2000
            });
          }
          //删除添加的input
          document.body.removeChild(inputZ);
        }
        return;
      };
      H5copyLink(con);

 

在 iOS 中 input 聚焦的时候会弹起键盘,对于复制操作交互体验很差,可以用以下方式禁止键盘的弹起。

<input type="text" readonly="readonly" />
<input type="text" οnfοcus="this.blur()" />
const input = document.createElement("input");
     input.readOnly = 'readonly';
$("#box").focus(function(){
    document.activeElement.blur();
});
 

 

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