在做一些国外站的时,很多时候我们需要将内容分享都 Facebook/Twitter/Instagram/Reddit ,以下根据前辈博客稍作了总结,不成文章.
- 分享到 Facebook
"http://www.facebook.com/sharer/sharer.php?u=" + url;
如果只是单纯的想分享一个链接到 facebook 去,而不添加过多的自定义内容,则只需要将需要分享的url作为参数的形式传递到facebook网站即刻.为了增加体验,可以先弹出一个弹框
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input id="share_button" type="button" value="share to facebook"/>
<script type="text/JavaScript">
/**
* 分享到 facebook
* @param url
* @param title「无用可忽略」
* @param w
* @param h
* @returns {Window}
*/
function popupwindow(url, title, w, h) {
wLeft = window.screenLeft ? window.screenLeft : window.screenX;
wTop = window.screenTop ? window.screenTop : window.screenY;
var left = wLeft + (window.innerWidth / 2) - (w / 2);
var top = wTop + (window.innerHeight / 2) - (h / 2);
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}
window.onload = function () {
document.getElementById('share_button').onclick = function () {
var shareUrl = "http://www.facebook.com/sharer/sharer.php?u=http://www.chinahub.guru/question/1";
popupwindow(shareUrl, 'facebook', 600, 400);
}
}
</script>
</body>
</html>
效果
2. 分享到 Twitter
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分享到 Twitter</title>
</head>
<body>
<input id="btn" type="button" value="分享到 Twitter">
<script>
var btn = document.getElementById("btn");
function shareToTwitter(url, title='', w=600, h=400) {
return window.open('http://twitter.com/share?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(title), '', 'left=0,top=0,width=550,height=450,personalbar=0,toolbar=0,scrollbars=0,resizable=0');
}
// 调用的方法
btn.onclick = function () {
shareToTwitter('https://www.baidu.com/', '哈哈哈,我要分享到 twitter 呀');
};
</script>
</body>
</html>
3. 分享到 Instagram
好像不行..参看 https://segmentfault.com/q/1010000014011671
4. 分享到 Reddit
暂不知怎么实现,但是客户提了这个需求
参考文章