您的位置:首页 > Web前端 > JavaScript

兼容IE与Firefox的js 复制代码

2009-12-01 00:00 639 查看
function copyCode(id){
var testCode=document.getElementById(id).value;
if(copy2Clipboard(testCode)!=false){
alert("生成的代码已经复制到粘贴板,你可以使用Ctrl+V 贴到需要的地方去了哦! ");
}
}
copy2Clipboard=function(txt){
if(window.clipboardData){
window.clipboardData.clearData();
window.clipboardData.setData("Text",txt);
}
else if(navigator.userAgent.indexOf("Opera")!=-1){
window.location=txt;
}
else if(window.netscape){
try{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch(e){
alert("您的firefox安全限制限制您进行剪贴板操作,请打开'about:config'将signed.applets.codebase_principal_support'设置为true'之后重试,相对路径为firefox根目录/greprefs/all.js");
return false;
}
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=txt;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);
}
}


[点击复制1]

复制内容1



[点击复制2]

复制内容2



[点击复制3]

复制内容3

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
下面的内容主要是应用了textarea作为内容载体,如果是div等,直接网页标记就需要用到innerText,但firefox火狐浏览器并不支持innerText,所以又要考虑如何让firefox支持innerText,这样以来就可以完美的实现了,具体的代码可以参考脚本之家的功能代码。
下一篇文章我们将介绍如何让firefox支持innerText的实现代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: