沒啥好說的,直接上代碼:
/** * 復制文本內容 * @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都是可以使用的~