一鍵復(fù)制功能在iOS手機(jī)實(shí)現(xiàn)

第一個(gè)方法

copyParameter(content) {     // content 要復(fù)制的參數(shù)
    var aux = document.createElement("input");
    aux.setAttribute("value", content);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("copy");
    document.body.removeChild(aux);
     alert("復(fù)制成功");
  
   },

如果這種方法不行換第二種

 const copyText = (text) => {
    // 數(shù)字沒有 .length 不能執(zhí)行selectText 需要轉(zhuǎn)化成字符串
    const textString = text.toString();
    let input = document.querySelector('#copy-input');
    if (!input) {
      input = document.createElement('input');
      input.id = "copy-input";
      input.readOnly = "readOnly";        // 防止ios聚焦觸發(fā)鍵盤事件
      input.style.position = "absolute";
      input.style.left = "-1000px";
      input.style.zIndex = "-1000";
      document.body.appendChild(input)
    }

    input.value = textString;
    // ios必須先選中文字且不支持 input.select();
    selectText(input, 0, textString.length);
    if (document.execCommand('copy')) {
      document.execCommand('copy');
      alert('已復(fù)制到粘貼板');
    }else {
      console.log('不兼容');
    }
    input.blur();

    // input自帶的select()方法在蘋果端無法進(jìn)行選擇,所以需要自己去寫一個(gè)類似的方法
    // 選擇文本。createTextRange(setSelectionRange)是input方法
    function selectText(textbox, startIndex, stopIndex) {
      if (textbox.createTextRange) {//ie
        const range = textbox.createTextRange();
        range.collapse(true);
        range.moveStart('character', startIndex);//起始光標(biāo)
        range.moveEnd('character', stopIndex - startIndex);//結(jié)束光標(biāo)
        range.select();//不兼容蘋果
      } else {//firefox/chrome
        textbox.setSelectionRange(startIndex, stopIndex);
        textbox.focus();
      }
    }
  };

鏈接:https://segmentfault.com/a/1190000019525962

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標(biāo)準(zhǔn)。 注意:講述HT...
    kismetajun閱讀 28,868評(píng)論 1 45
  • 前言 針對(duì)面試的 JavaScript 知識(shí)點(diǎn)整理 1.介紹一下js的數(shù)據(jù)類型有哪些,值是如何存儲(chǔ)的 JavaSc...
    Moon_f3e1閱讀 294評(píng)論 0 0
  • 基礎(chǔ)知識(shí) – 四大組件(生命周期,使用場景,如何啟動(dòng))java基礎(chǔ) – 數(shù)據(jù)結(jié)構(gòu),線程,mvc框架通信 – 網(wǎng)絡(luò)連...
    跑步的小男孩閱讀 284評(píng)論 0 2
  • 面試,無非都是問上面這些問題(挺多的 - -!),聘請(qǐng)中高級(jí)的安卓開發(fā)會(huì)往深的去問,并且會(huì)問一延伸二。以下我先提出...
    那年的歌閱讀 537評(píng)論 0 0
  • 目錄介紹 6.0.0.1 運(yùn)行時(shí)數(shù)據(jù)區(qū)域有哪些?Java虛擬機(jī)棧是做什么的?本地方法棧又是做什么的? 6.0.0....
    楊充211閱讀 493評(píng)論 0 1

友情鏈接更多精彩內(nèi)容