常规利用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