hexo 添加文章分享功能

hexo 默认主题 landscape 自带有分享功能,不过是分享到国外平台 Twitter Facebook Pinterest Google+,国内的分享并不支持。

本文去掉默认分享功能,添加国内平台分享。

  1. 修改 themes/landscape/_config.yml

    1
    2
    3
    4
    5
    6
    7
    # ...
    # CDN地址
    + cdn:
    + share:
    + js: 'https://cdn.bootcss.com/social-share.js/1.0.16/js/social-share.min.js'
    + css: 'https://cdn.bootcss.com/social-share.js/1.0.16/css/share.min.css'
    # ...
  2. 修改 themes/landscape/layout/_partial/after-footer.ejs

    在最开始添加如下内容(如果你的博客没使用 defer 延迟加载 js ,需要去掉 script 标签的 defer 属性):

    1
    2
    + <script src="<%= theme.cdn.share.js %>" defer></script>
    + <link href="<%= theme.cdn.share.css %>" rel="stylesheet">
  3. 修改 themes/landscape/layout/_partial/article.ejs

    1
    2
    - <a data-url="<%- post.permalink %>" data-id="<%= post._id %>" class="article-share-link"><%= __('share') %></a>
    + <div id="social-share" class="article-social-share"></div>
  4. 修改 themes/landscape/source/css/_partial/article.styl

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    + // 分享样式
    + small-screen-share()
    + float: none
    + text-align: center
    + margin: -10px 0 1em 0
    + border-bottom: 1px solid color-border
    + padding-bottom: 'calc(%s - 10px)' % line-height
    + font-size: 0.85em
    +
    + .article-social-share.social-share
    + float: right
    + margin: -7px 0 0 10px
    + -webkit-text-stroke-width: 0
    + @media mq-mobile
    + small-screen-share()
    + @media mq-tablet
    + small-screen-share()
    + .social-share-icon
    + border: 0 none
    + margin: 0 3px
  5. 修改 themes/landscape/source/js/script.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
         // Share
    - $('body').on('click', function () {
    - ...
    - ...
    - ...
    - box.css({
    - top: offset.top + 25,
    - left: offset.left
    - }).addClass('on');
    - });
    + let description = $('meta[name="description"]').attr('content') || '';
    + // QQ空间文字太长会出现 undefined
    + description = description.length > 110 ? (description.substring(0, 110) + '...') : description;
    + // 参考:https://github.com/overtrue/share.js
    + socialShare('#social-share', {
    + description : description, // 描述, 默认读取head标签:<meta name="description" content="PHP弱类型的实现原理分析" />
    + image : $('#main img').eq(0).attr('src'), // 图片, 默认取网页中第一个img标签
    + sites : ['weibo', 'qq', 'wechat', 'douban', 'qzone'], // 启用的站点
    + wechatQrcodeTitle : '微信扫一扫:分享', // 微信二维码提示文字
    + wechatQrcodeHelper : '<p>微信里点“发现”,扫一下</p><p>二维码便可将本文分享至朋友圈。</p>'
    + });
  6. 重启项目,文章底部会出现分享模块,效果如下图:

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-01-23/hexo-share/

如果您觉得文章不错,可以请我喝一杯咖啡!