剪貼板、複製、兼容
複製內容到剪貼板
是前端開發過程當中會常常遇到的一個需求,大部分同窗開發時每每會直接打開搜索框開始尋找別人寫好的組件庫,而聰明的同窗會開始思考問題:javascript
當產品使用場景並不大和複雜時,可使用這段 複製內容到剪貼板
代碼:前端
// 該源碼來自於 https://30secondsofcode.org const copyToClipboard = str => { const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); document.execCommand('copy'); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } };
瀏覽器提供了一個原生方法 document.execCommand('copy')
來實現 複製內容到剪貼板
,可是它有一個使用前提「須要選擇文本框或者輸入框時」,因此先建立一個 textarea
文本框並經過定位讓它不顯示在屏幕裏:java
const el = document.createElement('textarea'); el.value = str; el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el);
對建立好的 textarea
元素進行選中並使用複製裏面的文本內容,最後移除掉 textarea
元素。git
el.select(); document.execCommand('copy'); document.body.removeChild(el);
其實到此爲止就已經實現好了 複製內容到剪貼板
,跳過代碼分別是對兩個場景的優化,能夠根據產品開發的場景來選着是否使用這兩段代碼:github
移動設備上有一個問題 「當文本框被選中時,會彈出虛擬鍵盤」 會致使頁面出現閃爍,若是手機響應較慢甚至能夠看到虛擬鍵盤彈出和消失的過程。這段代碼的點睛之筆之一在於把輸入框設置爲只讀:瀏覽器
el.setAttribute('readonly', '');
小技巧:利用只讀屬性來防止彈出虛擬鍵盤。
代碼的另一處點睛之筆在於:若是用戶選中了某段文字後點擊複製內容到剪貼板
的複製操做這段選中的文字就會消失掉,肥肥的大拇指在手機屏幕像選着文本內容一直是一件挺讓人不舒服的操做,選中文字的消失十分影響用戶體驗。微信
咱們能夠利用 document.getSelection
一系列光標選中 API 來幫助咱們先記錄下用戶以前所選的文字對象:app
const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
再進行完複製操做後對 selected
進行判斷,並恢復先前記錄下用戶以前所選的文字對象:優化
if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); }
在困惑的城市裏總少不了並肩同行的
夥伴
讓咱們一塊兒成長。
點贊
。小星星
。m353839115
。
本文原稿來自 PushMeTop