动态分类条,可以根据页面变化而改变的分类列表展示方式

好久没有写魔改教程了,今天带来一个最近琢磨的一个分类条的显示。以前非常喜欢这种tab切换就能更换列表文章的显示方式,可是静态博客想要做到这一点真的是太难了,而且是原生html,不是vue。我的博客一直没有能够在首页展示分类的入口。起初因为分类比较少,但是现在已经很多了。那么一个展示分类的条就是非常必要的了。

这个分类条非常简约,原生js。魔改需要自己具备一定的魔改基础。

配置方式

分类的添加采取的是纯手工的方式,本人技术有限没有去翻Hexo的API,并且想要根据自己的心意进行排序,所以就只能手动来了。

新建文件

新建文件:themes/butterfly/layout/includes/categoryBar.pug

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CODE

#category-bar
.category-bar-items#category-bar-items
.category-bar-item(id='首页')
a(href="/") 首页
.category-bar-item(id='经验分享')
a(href="/categories/经验分享/") 经验分享
.category-bar-item(id='翻译内容')
a(href="/categories/翻译内容/") 翻译内容
.category-bar-item(id='资源中心')
a(href="/categories/资源中心/") 资源中心
.category-bar-item(id='优质推荐')
a(href="/categories/优质推荐/") 优质推荐
.category-bar-item(id='佳作推荐')
a(href="/categories/佳作推荐/") 佳作推荐
.category-bar-item(id='我的开发')
a(href="/categories/我的开发/") 我的开发
.category-bar-item(id='闲聊杂谈')
a(href="/categories/闲聊杂谈/") 闲聊杂谈
.category-bar-item(id='转载内容')
a(href="/categories/转载内容/") 转载内容
a.category-bar-more(href="/categories/") 更多

根据自己的需要进行修改。

引用文件

我们需要在首页和分类的页面引用我们的分类条

编辑themes/butterfly/layout/index.pug

+postUI上一行添加include includes/categoryBar.pug,并保持缩进相同。

引用文件

我们在分类页也需要引用。

编辑themes/butterfly/layout/category.pug,在#category下方添加以下代码

1
2
3
4
5
6
CODE
#category
.category-in-bar
.category-in-bar-tips
| 分类
include includes/categoryBar.pug

分类页代码引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
extends includes/layout.pug

block content
if theme.category_ui == 'index'
include ./includes/mixins/post-ui.pug
#recent-posts.recent-posts.category_ui
+postUI
include includes/pagination.pug
else
include ./includes/mixins/article-sort.pug
#category
.category-in-bar
.category-in-bar-tips
| 分类
include includes/categoryBar.pug
.article-sort-title= _p('page.category') + ' - ' + page.category
+articleSort(page.posts)
include includes/pagination.pug

引入js和css

如果没有引用过heoMainColor.css需要引用

1
2
CODE
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/zhheo/JS-Heo@main/mainColor/heoMainColor.css">

引用主css

1
2
CODE
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/zhheo/JS-Heo@main/categoryBar/categoryBar.css">

引用主js

1
2
CODE
<script async src="https://cdn.jsdelivr.net/gh/zhheo/JS-Heo@main/categoryBar/categoryBar.js"></script>

来自:https://blog.zhheo.com/p/bc61964d.html

以下为我的一些优化

引用的css,与js都没有压缩,所以我把css打包成了一个文件(复制到你的css文件即可)js不要压缩,不然会不生效

1
https://unpkg.zhimg.com/onexuezha_img@1.0.15/%E8%B5%84%E6%BA%90/css/custom.css

引用即可(其中有页脚透明代码,请自行删除)