js點擊復制文本內容


  沒啥好說的,直接上代碼:

/**
 * 復制文本內容
 * @param {*} cpStr 需要復制的文本內容
 */
function copyString (cpStr) {
  var orderNum = cpStr;
  // 數字沒有 .length 不能執行selectText 需要轉化成字符串
  var textString = orderNum.toString();
  var input = document.querySelector('#copy-input');
  if (!input) {
    input = document.createElement('input');
    input.id = "copy-input";
    input.readOnly = "readOnly";        // 防止ios聚焦觸發鍵盤事件
    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);
  console.log(document.execCommand('copy'), 'execCommand');
  if (document.execCommand('copy')) {
    document.execCommand('copy');
    utils.toasts('復制成功');
  }
  input.blur();

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


// 復制單號
$('#copy-btn').on('click', function () {
  var copyString = '123456';
  // 復制文本內容
  copyString(copyString);
})

  ios和android都是可以使用的~

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM