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();
});
 

 

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