之前發布過一篇文章原生 js 實現點擊按鈕復制文本,后來發現在ios的上失效。現又找到一個解決方案。
實現原理
采用.('copy')來實現復制到粘貼板功能
復制必須是選中input框的文字內容,然后執行.('copy')命令實現復制功能。
初步實現方案
const input = document.querySelector('#copy-input'); if (input) { input.value = text; if (document.execCommand('copy')) { input.select(); document.execCommand('copy'); input.blur(); alert('已復制到粘貼板'); } }
兼容性問題1、input 輸入框不能或者: none;如果需要隱藏輸入框可以使用定位脫離文檔流html實現復制到剪貼板,然后移除屏幕
#copy-input{ position: absolute;left: -1000px; z-index: -1000; }
2、ios下不能執行.('copy')
在ios設備下alert(.('copy'))一直返回false
查閱相關資料發現ios下input不支持input.();
因此拷貝的文字必須存在html實現復制到剪貼板,不能為空字符串,不然也不會執行復制空字符串的功能
參考這篇博客實現了ios下復制的功能
主要是使用.方法選中輸入框的文字
// input自帶的select()方法在蘋果端無法進行選擇,所以需要自己去寫一個類似的方法 // 選擇文本。createTextRange(setSelectionRange)是input方法 function selectText(textbox, startIndex, stopIndex) { if (textbox.createTextRange) {//ie const 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(); } }
3、ios設備上復制會觸發鍵盤彈出事件
給input加上只讀屬性
踩完以上的坑,總結的代碼如下
git地址
運行代碼
h5實現一鍵復制到粘貼板 兼容ios
h5實現一鍵復制到粘貼板 兼容ios
<script> const copyText = (text) => { // 數字沒有 .length 不能執行selectText 需要轉化成字符串 const textString = text.toString(); let 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); if (document.execCommand('copy')) { document.execCommand('copy'); alert('已復制到粘貼板'); }else { console.log('不兼容'); } input.blur(); // input自帶的select()方法在蘋果端無法進行選擇,所以需要自己去寫一個類似的方法 // 選擇文本。createTextRange(setSelectionRange)是input方法 function selectText(textbox, startIndex, stopIndex) { if (textbox.createTextRange) {//ie const 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(); } } }; // 復制文字 // 必須手動觸發 點擊事件或者其他事件,不能直接使用js調用!!! // copyText('h5實現一鍵復制到粘貼板 兼容ios') /*兼容性補充: 移動端: 安卓手機:微信(chrome)和幾個手機瀏覽器都可以用。 蘋果手機:微信里面和sarafi瀏覽器里也都可以, PC:sarafi版本必須在10.2以上,其他瀏覽器可以. 兼容性測試網站:https://www.caniuse.com/*/ </script>
原文:ZHAO_