JavaScript 实现 Hexo 中给时间久远的文章增加友好的提示(Pug)

JavaScript 实现 Hexo 中给时间久远的文章增加友好的提示(Pug)

发表于 2020/06/05 更新于 2020/06/07 359 字 2 分钟
AI 摘要 由 AI 自动生成

|

最近发现一直有流量会访问到我很早之前写的文章,但随着时间的变化,文章的内容可能已经不适用于现在了。比较喜欢 v2ex 的风格,对很久以前的文章增加一个 tip,告诉读者要注意文章的时效性。

https://www.v2ex.com/t/53623

本着一个对读者负责任的态度,希望读者可以注意到文章时效性的问题,能对文章有一个主观的判断,避免因为时效性问题而走弯路,所以我决定给 Hexo 时间久远文章加上一个友好的提示,因为我本人的博客是 Butterfly 的主题,所以只适配了 Butterfly,也许也适用于使用 Pug 渲染器的主题,大家可以随意取用。 使用 JavaScript 实现,只需修改 Butterfly 主题的两个文件。 在 themes/Butterfly/layout/includes/post 目录下新增一个 timecount.pug 文件,内容如下。

script.
  var now = new Date()
  now = now.getTime() // 当前时间戳

  var postinfo = document.getElementsByClassName("post-meta__date-created")[0]
  var postinfo__date_created = new Date(postinfo.title.split(" ")[1].replace(/-/,"/"))
  postinfo__date_created = postinfo__date_created.getTime() // 文章发布时间戳
  //console.log("文章创建时间",postinfo__date_created)

  var datepassing = parseInt(now - postinfo__date_created)
  //console.log("过期时间",datepassing)
  // 超过31天提示:3600*24*31*1000
  if(datepassing > 2678400000){
      var timecount = document.getElementsByClassName("post-timecount")[0]
      var out = parseInt(datepassing / 86400000)
      timecount.innerHTML = "<div class=\"note info\"><p><strong>文章有效性提示 Article Validity Tips</strong><br>这是一篇创建于 " + out + " 天前的文章,其中的信息可能已经有所发展或是发生改变。<br>This is an article that was created " + out + " days ago, and the information may have evolved or changed.</p></div>"
  }

{% note success %} 更新 2020 年 6 月 7 日:感谢 Los-Kos 的反馈,目前已修复文章页面目录不会展开的 BUG。 {% endnote %}

修改 themes/Butterfly/layout/post.pug 文件。这里我直接把整个文件放出来了,如果你没有修改过 post.pug,可以直接替换。

extends includes/layout.pug

block content
  article#post(class="")
    .post-timecount
    include includes/post/timecount.pug
    #article-container.post-content!=page.content
    include includes/post/post-copyright.pug
      .tag_share
        if (theme.post_meta.post.tags)
          .post-meta__tag-list
            each item, index in page.tags.data
              a(href=url_for(item.path)).post-meta__tags #[=item.name]
        !=partial('includes/share/index', {}, {cache:theme.fragment_cache})

    if theme.reward.enable
      !=partial('includes/post/reward', {}, {cache:theme.fragment_cache})

    //- ad
    if theme.ad && theme.ad.post
      .post-ad!=theme.ad.post

    include includes/pagination.pug
    if theme.related_post && theme.related_post.enable
      != related_posts(page,site.posts)
    if page.comments !== false
      include includes/comments/index.pug

好了,重新生成一下 hexo,看看效果。

hexo 时间久远文章提示

作者: 小谈谈
声明: 本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。