1、引入jQuery,相信大多數WordPress博客都已經引入了jQuery,那就可以直接進行第二步了.
2、在頁面底部,或者更確切的說,在引入jQuery庫的后面加上這樣一段JS,你就可以看到和本站一樣的效果了.
選中即分享的功能看上去比較高級,其實實現是相當簡單的,其中的會讓人頭大,一般人也不感興趣的原理這里就直接跳過,這個js文字選中后分享到新浪微博的功能我簡單的封裝了下,方法名是:$sinaMiniBlogShare
實例代碼如下:
- var miniBlogShare = function() {
- //指定位置駐入節點
- $('<img id="imgSinaShare" class="img_share" title="將選中內容分享到新浪微博" src="1328255868614.gif" /><img id="imgQqShare" class="img_share" title="將選中內容分享到騰訊微博" src="/1328255868314.png" />').appendTo('body');
- //默認樣式
- $('.img_share').css({
- display : 'none',
- position : 'absolute',
- cursor : 'pointer'
- });
- //選中文字
- var funGetSelectTxt = function() {
- var txt = '';
- if(document.selection) {
- txt = document.selection.createRange().text;
- } else {
- txt = document.getSelection();
- }
- return txt.toString();
- };
- //選中文字后顯示微博圖標
- $('html,body').mouseup(function(e) {
- if (e.target.id == 'imgSinaShare' || e.target.id == 'imgQqShare') {
- return
- }
- e = e || window.event;
- var txt = funGetSelectTxt(),
- sh = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
- left = (e.clientX - 40 < 0) ? e.clientX + 20 : e.clientX - 40,
- top = (e.clientY - 40 < 0) ? e.clientY + sh + 20 : e.clientY + sh - 40;
- if (txt) {
- $('#imgSinaShare').css({
- display : 'inline',
- left : left,
- top : top
- });
- $('#imgQqShare').css({
- display : 'inline',
- left : left + 30,
- top : top
- });
- } else {
- $('#imgSinaShare').css('display', 'none');
- $('#imgQqShare').css('display', 'none');
- }
- });
- //點擊新浪微博
- $('#imgSinaShare').click(function() {
- var txt = funGetSelectTxt(), title = $('title').html();
- if (txt) {
- window.open('http://v.t.sina.com.cn/share/share.php?title=' + txt + ' —— 轉載自:' + title + '&url=' + window.location.href);
- }
- });
- //點擊騰訊微博
- $('#imgQqShare').click(function() {
- var txt = funGetSelectTxt(), title = $('title').html();
- if (txt) {
- window.open('http://v.t.qq.com/share/share.php?title=' + encodeURIComponent(txt + ' —— 轉載自:' + title) + '&url=' + window.location.href);
- }
- });
- }();
可以看到$sinaMiniBlogShare方法有兩個參數,eleShare和eleContainer,其中,前一個參數是必須的,指的是文字選中后出現的浮動層元素(在本文demo中就是新浪眼睛圖標),后面一個參數指文字選擇的容器元素,可選參數,如果不設置則指document元素,也就是整個頁面文字選中都會觸發分享的功能.
假設新浪微博分享圖標的HTML如下:
- <img id="imgSinaShare" class="img_sina_share" title="將選中內容分享到新浪微博" src="http://simg.sinajs.cn/blog7style/images/common/share.gif" />
則直接使用如下代碼:
$sinaMiniBlogShare(document.getElementById("imgSinaShare"));
新聞熱點
疑難解答
圖片精選