在不少的網站,相信你們都有看到,點擊一個按鈕以後,就把對應的代碼或者地址放置到了粘貼板中,這種操做粘貼板的方法是什麼呢,下面就來跟你們分享一下;app
1 function copyToClipboard(elem) { 2 // create hidden text element, if it doesn't already exist 3 var targetId = "_hiddenCopyText_"; 4 var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; 5 var origSelectionStart, origSelectionEnd; 6 if (isInput) { 7 // can just use the original source element for the selection and copy 8 target = elem; 9 origSelectionStart = elem.selectionStart; 10 origSelectionEnd = elem.selectionEnd; 11 } else { 12 // must use a temporary form element for the selection and copy 13 target = document.getElementById(targetId); 14 if (!target) { 15 var target = document.createElement("textarea"); 16 target.style.position = "absolute"; 17 target.style.left = "-9999px"; 18 target.style.top = "0"; 19 target.id = targetId; 20 document.body.appendChild(target); 21 } 22 target.textContent = elem.textContent; 23 } 24 // select the content 25 var currentFocus = document.activeElement; 26 target.focus(); 27 target.setSelectionRange(0, target.value.length); 28 // copy the selection 29 var succeed; 30 try { 31 succeed = document.execCommand("copy"); 32 } catch(e) { 33 succeed = false; 34 } 35 // restore original focus 36 if (currentFocus && typeof currentFocus.focus === "function") { 37 currentFocus.focus(); 38 } 39 if (isInput) { 40 // restore prior selection 41 elem.setSelectionRange(origSelectionStart, origSelectionEnd); 42 } else { 43 // clear temporary content 44 target.textContent = ""; 45 } 46 return succeed; 47 } 48 49 //調用 50 copyToClipboard(document.getElementById("name"));//這裏傳入的參數是要把哪個標籤裏面的內容使用,就放入哪一個元素便可;
操做系統的東西,固然要原生的js兼容性更好了賽;看起來仍是很方便吧!網站