前言
最近在做一個按鈕,實現(xiàn)的效果是當點擊后復制url到黏貼板,但不是當前頁面url,而是對應一個元素的url,且一個頁面會有多個url。一開始找到一個方法,但是竟然只兼容IE瀏覽器,神奇了,竟然有只兼容IE的東西。后來發(fā)現(xiàn)一個zeroclipboard.js這個插件,但是怎么也搞不出那個效果,有點麻煩。
最后翻到了一個js封裝好的方法,有效!
想要實現(xiàn)的一個效果是,下面html代碼:
<tr> <td> <a id="copy_{$key}" onclick="getUrl('{$key}')">復制文件鏈接</a> <input id="file_{$key}" value="{$file.file_url}" style="margin-left: -9999px"/> </td></tr> 點擊復制文件鏈接這個按鈕,復制input框里的value值,是傳進去的一個url;首先點擊a標簽會觸發(fā)getUrl這個函數(shù);傳進去id用于找到對應的input然后取值(因為遍歷了多個td,有許多個input框一一對應去取)。
下面js代碼:
<pre><script type="application/javascript"> function getUrl(id) { if (copyToClipboard(document.getElementById("file_"+id))){ alert("成功復制到黏貼板!"); }else{ alert("復制到黏貼板失敗!"); } } function copyToClipboard(elem) { // create hidden text element, if it doesn't already exist var targetId = "_hiddenCopyText_"; var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; var origSelectionStart, origSelectionEnd; if (isInput) { // can just use the original source element for the selection and copy target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else { // must use a temporary form element for the selection and copy target = document.getElementById(targetId); if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target); } target.textContent = elem.textContent; } // select the content var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // copy the selection var succeed; try { succeed = document.execCommand("copy"); } catch(e) { succeed = false; } // restore original focus if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // restore prior selection elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // clear temporary content target.textContent = ""; } return succeed; }</script></pre>getUrl中調用了封裝好的copyToClipboard方法實現(xiàn)了功能。有一點的是html中input的樣式用style="margin-left: -9999px"進行隱藏,因為不知道為什么用type="hiden"或者display="none"去隱藏都只會獲取源代碼而不是動態(tài)的url遍歷出來的值。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
|
新聞熱點
疑難解答