基于JavaScript代码实现兼容各浏览器的设为首页和加入收藏
现在的浏览器越来越多,这就使得网页设计的兼容性要求越来越高,像常用的设为首页、加入收藏代码,一般的虽然简洁,但兼容性却非常不好,加入收藏和设为首页代码几乎各个网站都在头部放上一个,有没有效果先不管,需求应该是有的。
但是由于浏览器的兼容性问题,之前用的很多代码都失去效果,下面就给出一段能够兼容各个浏览器的代码,也不能够算是兼容,只能说在不支持的浏览器中能够给出提示,代码如下:
<!doctypehtml> <html> <head> <title>加入收藏和设为首页</title> <scripttype="text/javascript"> //加入收藏 functionAddFavorite(sURL,sTitle){ sURL=encodeURI(sURL); try{ window.external.addFavorite(sURL,sTitle); } catch(e){ try{ window.sidebar.addPanel(sTitle,sURL,""); } catch(e){ alert("加入收藏失败,请使用Ctrl+D进行添加,或手动在浏览器里进行设置."); } } } //设为首页 functionSetHome(url){ if(document.all){ document.body.style.behavior='url(#default#homepage)'; document.body.setHomePage(url); } else{ alert("您好,您的浏览器不支持自动设置页面为首页功能,请您手动在浏览器里设置该页面为首页!"); } } </script> </head> <body> <ahref="javascript:void(0)">设为首页</a> <ahref="javascript:void(0)">加入收藏</a> </body> </html>
以上代码简短易懂,可以兼容各个浏览器加入收藏和设为首页,有问题欢迎提出,小编会及时和大家联系的,谢谢!
下面给大家分享一段jquery代码实现加入收藏夹功能
//设为首页 functionSetHomePage(){ if(document.all){ document.body.style.behavior='url(#default#homepage)'; document.body.setHomePage('http://www.87cool.com'); } elseif(window.sidebar){ if(window.netscape){ try{ netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch(e){ alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入about:config,然后将项signed.applets.codebase_principal_support值该为true"); } } varprefs=Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage','http://www.87cool.com'); } } //加入收藏夹 functionAddFavorite(){ vartitle=document.title; varurl=location.href; if(window.sidebar){ window.sidebar.addPanel(title,url,""); }elseif(document.all){ window.external.AddFavorite(url,title); }else{ returntrue; } }