2013-10-26 40 views
9

我是新來的網站開發人員,並試圖弄清楚如何讓我的用戶在鏈接上點擊時自動將代碼複製到他/她的鼠標(剪貼板)中使用HTML,PHP或JavaScript)。例如,我試圖創建這個個人網站,當用戶點擊我網站上的鏈接或按鈕時,它應該自動將該文本代碼複製到剪貼板。我曾見過像retailmenot.com網站這樣做:例: - enter image description here單擊鏈接或按鈕時複製文本

請告訴我用一個例子,如果你能


更新時間:

<!DOCTYPE html> 
<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> 
</script> 
<script> 


$("#link").click(function(){ 
    var holdtext = $("#clipboard").innerText; 
    Copied = holdtext.createTextRange(); 
    Copied.execCommand("Copy"); 
}); 


</script> 
</head> 
<body> 

<hr> 
<a href="http://www.w3schools.com" style="font-family:arial;color:black;font-size:25px;">Click here to copy the Code</a> <button onclick="copyToClipboard()">Copy Text</button> 
<hr> 

</body> 
</html> 
+0

我不認爲JavaScript有任何內置的方式複製到/從剪貼板。有一些基於Flash的解決方案。 – Barmar

+1

長時間的討論:http://stackoverflow.com/questions/400212/how-to-copy-to-the-clipboard-in-javascript/ –

回答

0

嘗試。

$("#link").click(function(){ 
    var holdtext = $("#clipboard").innerText; 
    Copied = holdtext.createTextRange(); 
    Copied.execCommand("Copy"); 
}); 
+0

更好看一下http://stackoverflow.com/questions/127040 – Manwal

+0

這隻適用於IE(http://stackoverflow.com/questions/21572682/createtextrange-is-not-woring-in-chrome) – Lego

3

以下是可能可以幫助您或將來引薦者的功能。

function copyToClipboard(id) { 
    var text = $("#td_id_" + id).text(); //getting the text from that particular Row 
    //window.prompt("Copy to clipboard: Ctrl+C, Enter", text); 
    if (window.clipboardData && window.clipboardData.setData) { 
     // IE specific code path to prevent textarea being shown while dialog is visible. 
     return clipboardData.setData("Text", text); 

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) { 
     var textarea = document.createElement("textarea"); 
     textarea.textContent = text; 
     textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge. 
     document.body.appendChild(textarea); 
     textarea.select(); 
     try { 
      return document.execCommand("copy"); // Security exception may be thrown by some browsers. 
     } catch (ex) { 
      console.warn("Copy to clipboard failed.", ex); 
      return false; 
     } finally { 
      document.body.removeChild(textarea); 
     } 
    } 
    } 

單元測試全部瀏覽器未完成。

相關問題