實現單個頁面,多個百度分享(動態修改百度分享連結)
阿新 • • 發佈:2019-01-29
在我編寫文章列表頁程式碼的時候,想實現每一條文章都有一個分享按鈕,此處用到百度分享。百度分享官網:http://share.baidu.com/code/advance。
官網給出的完整程式碼只適合分享單個頁面,顯然不符合我的需求。仔細閱讀文件之後,發現在通用設定項的解析裡有這麼一項:
有了這項設定,我們可以很容易地改變window._bd_share_config 裡的設定。
步驟:
1、設定a元素的屬性(data-id,data-title)方便獲取對應連結的值。
2、宣告全域性變數。
3、為每個.bdsharebuttonbox a繫結mouseover事件,利用該事件來配置id跟title。
4、配置window._bd_share_config的common屬性,利用onBeforeClick來進行動態配置。
5、引入必須要的js。
具體程式碼:
//這裡是一個for迴圈
{for ....}
<div class="fl ml10 bdsharebuttonbox" data-tag="share_1">
<a class="bds_qzone" data-cmd="qzone" href="#" data-id="{$t[itemid]}" data-title="{$t[title]}"></a>
<a class="bds_tsina" data-cmd="tsina" data-id="{$t[itemid]}" data-title="{$t[title]}" ></a>
</div>
{/for}
<script>
//宣告全域性變數
var shareId = "",title='';
//全域性變數賦值,便於後邊更改配置
$(function () {
$(".bdsharebuttonbox a").mouseover(function () {
shareId = $(this).attr("data-id");
title = $(this).attr("data-title" );
});
});
function SetConf(cmd, config) {
if (ShareId) {
config.bdUrl = "https://www.xxx.com/news/" + shareId + '.html';
config.bdText = title;
}
return config;
}
window._bd_share_config = {
common : {onBeforeClick:SetConf},
share : [{"bdSize" : 12}],
slide : [{bdImg : 0,bdPos : "right",bdTop : 100}],//設定了這一項,頁面右邊會出現一個分享的浮窗,該浮窗只能分享當前設定的bdUrl
image : [{viewType : 'list',viewPos : 'top',viewColor : 'black',viewSize : '12',viewList : ['qzone','tsina','huaban','tqq','renren']}],
selectShare : [{
"bdselectMiniList" : ['qzone','tqq','kaixin001','bdxc','tqf']
}]
}
//以下程式碼是必須
with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>
為了方便使用,寫了一個簡單的jquery外掛:
(function ($) {
$.fn.share = function (options) {
var settings = {
text: '',
url:''
};
if (options) {
$.extend(settings, options);
}
window._bd_share_config = {
common : {
bdText:settings.text,
bdUrl:setting.url
},
share : [{
"bdSize" : 16
}],
}
}
with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
})(jQuery)
使用方法
<script type="text/javascript" src="share.js"></script>
<script type="text/javascript">$(".bdsharebuttonbox").share({title:'{$title}',url:'{$linkurl}'}); </script>