用JavaScript实现加入书签/收藏本页功能 addBookmark(url, title)

来源:互联网 发布:centos识别不到硬盘 编辑:程序博客网 时间:2024/05/21 09:39

转载请注明出处:http://blog.csdn.net/u012124764/article/details/50100313
原文:http://buffernow.com/create-bookmark-link-using-javascript/

这篇文章是关于如何给博客或者网站添加 加入书签/收藏本页 功能,以下代码支持的浏览器有 IE, Mozilla Firefox 和 Opera(注:Chrome和Safari出于安全考虑,不支持通过JavaScript添加书签,必须按Ctrl+D/Command+D/Ctrl+B手动添加

addBookmark(url, title)

function addBookmark(url, title){if (!url) {url = window.location}    if (!title) {title = document.title}    var browser=navigator.userAgent.toLowerCase();    if (window.sidebar) { // Mozilla, Firefox, Netscape        window.sidebar.addPanel(title, url,"");    } else if( window.external) { // IE or chrome        if (browser.indexOf('chrome')==-1){ // ie            window.external.AddFavorite( url, title);        } else { // chrome            alert('Please Press CTRL+D (or Command+D for macs) to bookmark this page');        }    }    else if(window.opera && window.print) { // Opera - automatically adds to sidebar if rel=sidebar in the tag        return true;    }    else if (browser.indexOf('konqueror')!=-1) { // Konqueror        alert('Please press CTRL+B to bookmark this page.');    }    else if (browser.indexOf('webkit')!=-1){ // safari        alert('Please press CTRL+B (or Command+D for macs) to bookmark this page.');    } else {        alert('Your browser cannot add bookmarks using this link. Please add this link manually.')    }}

可以通过按钮或链接来调用以上代码:

通过按钮调用

<input type="button" value="bookmark me"onclick="addBookmark('http://buffernow.com','buffer now');"/>

通过链接调用

<a href="#" onclick="addBookmark('http://buffernow.com','buffer now')">收藏本页</a>

完整的HTML代码如下:

<html><head> <script type="text/javascript">function addBookmark(url, title){if (!url) {url = window.location}    if (!title) {title = document.title}    var browser=navigator.userAgent.toLowerCase();    if (window.sidebar) { // Mozilla, Firefox, Netscape        window.sidebar.addPanel(title, url,"");    } else if( window.external) { // IE or chrome        if (browser.indexOf('chrome')==-1){ // ie            window.external.AddFavorite( url, title);        } else { // chrome            alert('Please Press CTRL+D (or Command+D for macs) to bookmark this page');        }    }    else if(window.opera && window.print) { // Opera - automatically adds to sidebar if rel=sidebar in the tag        return true;    }    else if (browser.indexOf('konqueror')!=-1) { // Konqueror        alert('Please press CTRL+B to bookmark this page.');    }    else if (browser.indexOf('webkit')!=-1){ // safari        alert('Please press CTRL+B (or Command+D for macs) to bookmark this page.');    } else {        alert('Your browser cannot add bookmarks using this link. Please add this link manually.')    }}</script></head><body><input type="button" value="bookmark me"onclick="addBookmark('http://buffernow.com', 'buffer Now');"/></body></html>
0 0
原创粉丝点击