原生 js,兼容所有的瀏覽器(ie,chrome,firefox),值得收藏。
函數如下:
function addFavorite(obj, opts){ var _t, _u; if(typeof opts != 'object'){ _t = document.title; _u = location.href; }else{ _t = opts.title || document.title; _u = opts.url || location.href; } try{ window.external.addFavorite(_u, _t); }catch(e){ if(window.sidebar){ obj.href = _u; obj.title = _t; obj.rel = 'sidebar'; }else{ alert('抱歉,您所使用的瀏覽器無法完成此操作。\n\n請使用 Ctrl + D 將本頁加入收藏夾!'); } } }
參數說明:
1、第一個參數必須,指代觸發事件對象,一般為 this;
2、第二個參數是對象,可選項。對象有兩個屬性 title 和 url(兩個屬性都是可選項)。
使用方法:
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"/> <title>收藏本站</title> </head> <body> <a href="javascript:;" onclick="addFavorite(this);">收藏本站</a> </body> </html>
PS:
網上那些收藏本站的代碼,經博主測試發現在 firefox 下面有些問題,原因是 addPanel 這個方法在 firefox24 以后就沒有了,解決方法是給 a 標簽添加 rel=”sidebar”,同時給 href 和 title 屬性賦值。