常規利用JS編寫的網頁複製功能只對IE有效,無法做到相容其它瀏覽器,程式碼如下:

function copyToClipBoard(){
var clipBoardContent="";
clipBoardContent+=document.getElementById("giftNumber").value; //可以是任何html ElementId,自己設定
if(window.clipboardData){
window.clipboardData.clearData();
window.clipboardData.setData("Text", clipBoardContent);
alert("已成功複製!");
}else if(navigator.userAgent.indexOf("Opera") != -1){
window.location = clipBoardContent;
alert("複製失敗"); //連結跳轉
}else if (window.netscape){
try{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}catch (e){
alert("您的當前瀏覽器設定已關閉此功能!請按以下步驟開啟此功能!\n新開一個瀏覽器,在瀏覽器位址列輸入'about:config'並回車。\n然後找到'signed.applets.codebase_principal_support'項,雙擊後設置為'true'。\n宣告:本功能不會危極您計算機或資料的安全!");
}
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
trans.addDataFlavor('text/unicode');
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
var copytext = clipBoardContent;
str.data = copytext;
trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid = Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}else if(navigator.userAgent.indexOf("Safari") != -1){
$("#copyTip").html("您使用的瀏覽器不支援複製功能,請使用右鍵複製").show();
//alert("您使用的瀏覽器不支援複製功能,請使用右鍵複製")
}
}

ZeroClipboard是利用flash為媒介實現相容各瀏覽器複製功能一款jquery外掛(測試通過瀏覽器IE6-8/chrome27/firefox22/safari 5.1.5/opera12.12),通過簡單的呼叫實現複製功能:

$(document).ready(function() {
var clip = new ZeroClipboard($("#d_clip_button"), {
moviePath: "ZeroClipboard.swf"
}); clip.on('load', function (client) {
debugstr("Flash movie loaded and ready.");
}); clip.on('noFlash', function (client) {
$(".demo-area").hide();
debugstr("Your browser has no Flash.");
}); clip.on('wrongFlash', function (client, args) {
$(".demo-area").hide();
debugstr("Flash 10.0.0+ is required but you are running Flash " + args.flashVersion.replace(/,/g, "."));
}); clip.on('complete', function (client, args) {
debugstr("Copied text to clipboard: " + args.text);
}); // jquery stuff (optional)
function debugstr(text) {
$("#d_debug").append($("<p>").text(text));
} });

demo下載

注意:

1、需以web形式訪問才有效。

2、IE下複製按鈕為可點選的那層DOM最後一級(不是最後一級有時會出問題,如把b換成span在IE下無效)
<button id="copyBtn" class="my_clip_button" title="Click me to copy to clipboard." data-clipboard-target="giftNumber" data-clipboard-text="Default clipboard text from attribute"><b>Copy To Clipboard...</b></button>

參考資料:

http://jonrohan.github.io/ZeroClipboard/
https://github.com/zeroclipboard/ZeroClipboard
http://js8.in/407.html