现在不使用ZeroClipboard我们也能实现复制功能(转)
現(xiàn)在不使用ZeroClipboard我們也能實現(xiàn)
首先,我們保證頁面結(jié)構(gòu)不變,但不在引入ZeroClipboard插件:
1 <input type="text" name="" id="J_TextIn" value="Copy Test."> 2 <input type="button" value="Copy" id="J_DoCopy">?
然后,我們使用?document.execCommamd來對內(nèi)容進行復制:
(function(){2 var btn = document.getElementById('J_DoCopy'),3 text = document.getElementById('J_TextIn');4 btn.onclick = function(){5 var transfer = document.getElementById('J_CopyTransfer');6 if (!transfer) {7 transfer = document.createElement('textarea');8 transfer.id = 'J_CopyTransfer';9 transfer.style.position = 'absolute'; 10 transfer.style.left = '-9999px'; 11 transfer.style.top = '-9999px'; 12 document.body.appendChild(transfer); 13 } 14 transfer.value = text.value; 15 transfer.focus(); 16 transfer.select(); 17 document.execCommand('Copy', false, null); 18 }; 19 })();
接著,我們在瀏覽器中瀏覽,和使用ZeroClipboard時一樣的去操作,效果是一樣的。但是,這段代碼的正確執(zhí)行是有限制的,因為?document.execCommand?在Chrome中支持的比較晚,所以要求Chrome版本必須是43及以后。
最后,再補充說明一下,使用?document.execCommand?來實現(xiàn)復制內(nèi)容時,過渡被復制內(nèi)容的?textarea?標簽(即:動態(tài)創(chuàng)建的那個textarea標簽),在復制可輸入?yún)^(qū)域(input:text,textarea)的內(nèi)容時并不是必須的,可以直接簡化為:
1 (function(){2 var btn = document.getElementById('J_DoCopy'),3 text = document.getElementById('J_TextIn');4 btn.onclick = function(){5 text.focus();6 text.select();7 document.execCommand('Copy', false, null);8 text.blur();9 }; 10 })();?
考慮到實際使用中,我們可能需要復制一些非編輯區(qū)域提供的內(nèi)容(比如:一個a標簽的鏈接地址等),所以增加了一個過渡的texearea,似乎更保險,更靈活一些。
此外,我再測試過程中,曾試圖將過渡的那個textarea設置為不可見的?visibility:hidden;?,卻發(fā)現(xiàn)復制功能失效了,所以這里需要注意一下...
轉(zhuǎn)載于:https://www.cnblogs.com/xupeiyu/p/4882349.html
總結(jié)
以上是生活随笔為你收集整理的现在不使用ZeroClipboard我们也能实现复制功能(转)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。