优选主流主机商
任何主机均需规范使用

如何在WordPress中将内容一键分享到新浪和腾讯微博

本文实例讲述了Wordpress将选中内容分享到新浪腾讯微博的方法。分享给大家供大家参考。具体方法如下:

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

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

选中即分享的功能看上去比较高级,其实实现是相当简单的,其中的会让人头大,一般人也不感兴趣的原理这里就直接跳过,这个js文字选中后分享到新浪微博的功能我简单的封装了下,方法名是:$sinaMiniBlogShare

实例代码如下:

  1. var miniBlogShare = function() {
  2. //指定位置驻入节点
  3. $(‘<img id=”imgSinaShare”  title=”将选中内容分享到新浪微博” src=”1328255868614.gif” /><img id=”imgQqShare”  title=”将选中内容分享到腾讯微博” src=”/1328255868314.png” />’).appendTo(‘body’);
  4.  
  5. //默认样式
  6. $(‘.img_share’).css({
  7. display : ‘none’,
  8. position : ‘absolute’,
  9. cursor : ‘pointer’
  10. });
  11.  
  12. //选中文字
  13. var funGetSelectTxt = function() {
  14. var txt = ”;
  15. if(document.selection) {
  16. txt = document.selection.createRange().text;
  17. } else {
  18. txt = document.getSelection();
  19. }
  20. return txt.toString();
  21. };
  22.  
  23. //选中文字后显示微博图标
  24. $(‘html,body’).mouseup(function(e) {
  25. if (e.target.id == ‘imgSinaShare’ || e.target.id == ‘imgQqShare’) {
  26. return
  27. }
  28. e = e || window.event;
  29. var txt = funGetSelectTxt(),
  30. sh = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0,
  31. left = (e.clientX – 40 < 0) ? e.clientX + 20 : e.clientX – 40,
  32. top = (e.clientY – 40 < 0) ? e.clientY + sh + 20 : e.clientY + sh – 40;
  33. if (txt) {
  34. $(‘#imgSinaShare’).css({
  35. display : ‘inline’,
  36. left : left,
  37. top : top
  38. });
  39. $(‘#imgQqShare’).css({
  40. display : ‘inline’,
  41. left : left + 30,
  42. top : top
  43. });
  44. } else {
  45. $(‘#imgSinaShare’).css(‘display’, ‘none’);
  46. $(‘#imgQqShare’).css(‘display’, ‘none’);
  47. }
  48. });
  49.  
  50. //点击新浪微博
  51. $(‘#imgSinaShare’).click(function() {
  52. var txt = funGetSelectTxt(), title = $(‘title’).html();
  53. if (txt) {
  54. window.open(‘http://v.t.sina.com.cn/share/share.php?title=’ + txt + ‘ —— 转载自:’ + title + ‘&url=’ + window.location.href);
  55. }
  56. });
  57.  
  58. //点击腾讯微博
  59. $(‘#imgQqShare’).click(function() {
  60. var txt = funGetSelectTxt(), title = $(‘title’).html();
  61. if (txt) {
  62. window.open(‘http://v.t.qq.com/share/share.php?title=’ + encodeURIComponent(txt + ‘ —— 转载自:’ + title) + ‘&url=’ + window.location.href);
  63. }
  64. });
  65. }();

可以看到$sinaMiniBlogShare方法有两个参数,eleShare和eleContainer,其中,前一个参数是必须的,指的是文字选中后出现的浮动层元素(在本文demo中就是新浪眼睛图标),后面一个参数指文字选择的容器元素,可选参数,如果不设置则指document元素,也就是整个页面文字选中都会触发分享的功能.

假设新浪微博分享图标的HTML如下:

  1. <img id=”imgSinaShare” class=”img_sina_share” title=”将选中内容分享到新浪微博” src=”http://simg.sinajs.cn/blog7style/images/common/share.gif” />

则直接使用如下代码:

  1. $sinaMiniBlogShare(document.getElementById(“imgSinaShare”));

希望本文所述对大家的WordPress建站有所帮助。

未经允许不得转载:搬瓦工中文网 » 如何在WordPress中将内容一键分享到新浪和腾讯微博