WordPress博客选中的文字转发到微博的实现方法


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

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

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

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

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

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

var miniBlogShare = function() {
//指定位置驻入节点
$('<img id="imgSinaShare" class="img_share" title="将选中内容分享到新浪微博" src="http://upload.chinaz.com/2012/0203/1328255868614.gif" /><img id="imgQqShare" class="img_share" title="将选中内容分享到腾讯微博" src="http://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('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);
}
});
}();

是不是很简单呀?

赶紧选中本文的标题,在微博上通知你的好友来围观吧,哈哈~

PS:最后,说一句,其实这个方法不仅仅适用于WordPress,JS是通用的,你可以把这段 JS 挂载到任何网站上都可以得到相同的效果。

PS2:最最最后,再说一句,麻烦各位在使用前,把JS里的两张微博的图片路径替换成自己的地址,因为小站流量有限,大家帮我省着点花呗,嘿嘿。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3