2013-10-26 3 views
9

私はウェブサイト開発が初めてで、リンク上をクリックすると自動的にコードを自分のマウス(クリップボード)にコピーできますhtml、php、またはjavascriptを使用して)。たとえば、この個人用Webサイトを作成しようとしています。ユーザーがWebサイトのリンクまたはボタンをクリックすると、そのテキストコードがクリップボードに自動的にコピーされます。例:私は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); 
     } 
    } 
    } 

すべてのブラウザでユニットテストは行われません。

関連する問題