1 // 點擊復制信息 2 copyTxt (txt) { 3 var u = navigator.userAgent 4 var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 5 // 要先判斷當前是什么系統,否則會報錯,無法執行語句 6 if (isAndroid) { 7 let _input = document.createElement('input')// 直接構建input 8 _input.value = txt// 設置內容 9 document.body.appendChild(_input)// 添加臨時實例 10 _input.select()// 選擇實例內容 11 document.execCommand('Copy')// 執行復制 12 document.body.removeChild(_input)// 刪除臨時實例 13 if (document.execCommand('Copy')) { 14 Toast('復制成功') 15 } else { 16 Toast('復制失敗,請手動復制') 17 } 18 } else { 19 // 數字沒有 .length 不能執行selectText 需要轉化成字符串 20 const textString = txt.toString() 21 let input = document.querySelector('#copy-input') 22 if (!input) { 23 input = document.createElement('input') 24 input.id = 'copy-input' 25 input.readOnly = 'readOnly' 26 input.style.position = 'absolute' 27 input.style.left = '-1000px' 28 input.style.zIndex = '-1000' 29 document.body.appendChild(input) 30 } 31 32 input.value = textString 33 // ios必須先選中文字且不支持 input.select() 34 this.selectText(input, 0, textString.length) 35 console.log(document.execCommand('copy'), 'execCommand') 36 if (document.execCommand('copy')) { 37 document.execCommand('copy') 38 Toast('復制成功') 39 } else { 40 Toast('復制失敗,請手動輸入') 41 } 42 input.blur() 43 document.body.removeChild(input) 44 // input自帶的select()方法在蘋果端無法進行選擇,所以需要自己去寫一個類似的方法 45 // 選擇文本。createTextRange(setSelectionRange)是input方法 46 } 47 }, 48 selectText (textbox, startIndex, stopIndex) { 49 if (textbox.createTextRange) { // ie 50 const range = textbox.createTextRange() 51 range.collapse(true) 52 range.moveStart('character', startIndex)// 起始光標 53 range.moveEnd('character', stopIndex - startIndex)// 結束光標 54 range.select() // 不兼容蘋果 55 } else { // firefox/chrome 56 textbox.setSelectionRange(startIndex, stopIndex) 57 textbox.focus() 58 } 59 }