• [织梦吧]唯一域名:www.upgvv.com,织梦DedeCMS学习平台.

当前位置: > CMS教程 > Wordpress教程 >

WordPress将选中文字转发到微博

来源: www.upgvv.com 编辑:织梦吧 时间:2013-02-04点击:

最近在看腾讯新闻的时候,无意中发现,当我选中新闻中的文字的时候,鼠标右上角会显示一个“转播至微博”的按钮,点击后就会将选中的文字转发到微博上。这是一个很不错的用户体验,如果能把它引入到WordPress博客中,那不是很好吗?

为此我还特地去注册了一个腾讯微博开放平台的开发者,当我开始阅读开发文档的时候,才发现,他妹的,腾讯官方已经推出一个相同功能的应用,叫作 “Q-Share”,再翻阅了一下其他资料,原来已经有前辈写出了js页面文字选中后分享到新浪微博的方法,那我就省力多了,两者结合一下,把新浪微博和腾讯微博两个按钮都加上了,然后闲的蛋疼的我又把它翻译成了jQuery的方法。

效果的话就可以看本站了,选中任何文字,就会在右上角显示两个微博按钮,点击试试吧。

实现的方法也很简单,只需要两步:

1、引入jQuery,相信大多数WordPress博客都已经引入了jQuery,那就可以直接进行第二步了。

2、在页面底部,或者更确切的说,在引入jQuery库的后面加上这样一段JS,你就可以看到和本站一样的效果了。

var miniBlogShare = function() {
    //指定位置驻入节点
    $('<img id="imgSinaShare" class="img_share" title="将选中内容分享到新浪微博" src="https://upload.chinaz.com/2012/0203/1328255868614.gif" /><img id="imgQqShare" class="img_share" title="将选中内容分享到腾讯微博" src="https://upload.chinaz.com/2012/0203/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('https://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('https://v.t.qq.com/share/share.php?title=' + encodeURIComponent(txt + ' —— 转载自:' + title) + '&url=' + window.location.href);
        }
    });
}();