js实现网页google、twitter、facebook分享功能代码菜鸟教程

在开发一个针对国外的网站,里面需要实现一个分享到Facebook/Twitter/Google+等的功能, facebook,twitter,Google虽说在国内不是如同微博,朋友圈那样非常的盛行,但是工作中涉及到国外的业务时候就必须要去研究。下面为大家分享如何实现 ?

js代码:

function share(type){//分享
    var toOpen=function(url){
        var option='toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=600, height=450,top=100,left=350';
        option=isDevice()=="Web"?option:'';
        window.open(
            url,'_blank',option,
        );
    }
    var href=encodeURIComponent(document.location.href);
    var title=encodeURIComponent(document.title);
    switch(type){
        case 'facebook'://分享到Facebook的代码
            toOpen('http://www.facebook.com/sharer.php?u='+href+'&t='+title);
            break;
        case 'google'://分享到Google的代码
            toOpen('http://www.google.com/bookmarks/mark?op=add&bkmk='+href+'&title='+title);
            break;
        case 'twitter'://分享到twitter的代码
            toOpen('http://twitter.com/home?status='+href+' '+title);
            break;
        case 'yahoo'://分享到yahoo
            toOpen('http://myweb2.search.yahoo.com/myresults/bookmarklet?u='+href+'&t='+title);
            break;
        case 'linkedin'://分享到linkedin
            toOpen('http://www.linkedin.com/shareArticle?mini=true&url='+href+'&title='+title);
            break;
    }    
}

meta标签:

在你的html页面的head标签里加入这几个meta标签 :以twitter和facebook为例。添加对应的meta可以实现分享固定的描述,图片等信息哦。

<!-- twitter-->
<meta name="twitter:title"   content="@ViewBag.Title" />
<meta name="twitter:description"   content="@ViewBag.Description" />
<meta name="twitter:image" content="@ViewBag.ShareImg" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:url"   content="当前分享的链接--可要可不要" />
 
<!-- facebook -->    
<meta property="og:image" content="@ViewBag.ShareImg" />     
<meta property="og:locale" content="en-US" />
<meta property="og:type"   content="website" />
<meta property="og:url"   content="当前分享的链接--可要可不要" />

当然也有比较全面的分享插件,比如:share.js。一键分享到微博、QQ空间、QQ好友、微信、腾讯微博、豆瓣、Facebook、Twitter、Linkedin、Google+、点点等

github地址:https://github.com/overtrue/share.js/

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1265
0 评论
1.2k

发表评论

!