前言

本文教程主要针对 Hexo Butterfly 主题博客,在 Butterfly 主题中,文章标签页标签侧边栏都有文章标签的词云图,但仅仅用字体大小表示某个标签下的文章数量是不明显的,可以在这个基础上加上表示某个标签下文章数的上下标,其中 <sup> 表示上标,<sub> 表示下标。

Butterfly 标签云增加文章数上下标

修改 page.js

  1. 打开 \themes\butterfly\layout\includes\page\tags.pug 文件和 \themes\butterfly\layout\includes\widget\card_tags.pug 文件,发现绘制彩色标签云都是使用了 cloudTags 函数。

    另外一个绘制标签云的 tagcloud 函数是 hexo 自带的,有兴趣的可以到 \node_modules\hexo\lib\plugins\helper\tagcloud.js 研究,这里不多介绍。

  2. 搜索 cloudTags 函数,可以在 \themes\butterfly\scripts\helpers\page.js 找到绘制标签云的代码,增加 <sup>${tag.length}</sup><sub>${tag.length}</sub> 可绘制表示标签文章数的上下标。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    hexo.extend.helper.register('cloudTags', function (options = {}) {
    const theme = hexo.theme.config
    const env = this
    let source = options.source
    const minfontsize = options.minfontsize
    const maxfontsize = options.maxfontsize
    const limit = options.limit
    const unit = options.unit || 'px'

    let result = ''
    if (limit > 0) {
    source = source.limit(limit)
    }

    const sizes = []
    source.sort('length').forEach(tag => {
    const { length } = tag
    if (sizes.includes(length)) return
    sizes.push(length)
    })

    const length = sizes.length - 1
    source.forEach(tag => {
    const ratio = length ? sizes.indexOf(tag.length) / length : 0
    const size = minfontsize + ((maxfontsize - minfontsize) * ratio)
    let style = `font-size: ${parseFloat(size.toFixed(2))}${unit};`
    const color = 'rgb(' + Math.floor(Math.random() * 201) + ', ' + Math.floor(Math.random() * 201) + ', ' + Math.floor(Math.random() * 201) + ')' // 0,0,0 -> 200,200,200
    style += ` color: ${color}`
    - result += `<a href="${env.url_for(tag.path)}" style="${style}">${tag.name}</a>`
    + result += `<a href="${env.url_for(tag.path)}" style="${style}">${tag.name}<sup>${tag.length}</sup></a>`
    })
    return result
    })

Hexo 三连

执行 Hexo 三连

1
hexo clean && hexo g && hexo s