Hexo-NexT代码块折叠

有些时候,代码块很长,我们可以通过代码块折叠来减少全文的长度,使得阅读全文更加方便。

主题版本:NexT-7.1.2

2020-03-01更新:现在NexT主题已经更新到7.7.1,在最新主题下配置这个代码块折叠的方法详见:Hexo-NexT 版本更新记录

新建内建标签

新建hexo-theme-next/scripts/custom/fold_tag.js

1
2
3
4
5
6
7
8
/* global hexo */
// Usage: {% fold 点击显/隐内容 %} Something {% endfold %}
function fold (args, content) {
var text = args[0];
if(!text) text = "点击显/隐";
return '<div><div class="fold_hider"><div class="close hider_title">' + text + '</div></div><div class="fold">\n' + hexo.render.renderSync({text: content, engine: 'markdown'}) + '\n</div></div>';
}
hexo.extend.tag.register('fold', fold, {ends: true});

添加折叠代码块js

新建hexo-theme-next/source/custom/fold_action.js

1
2
3
4
5
6
7
8
$(document).ready(function(){
$(document).on('click', '.fold_hider', function(){
$('>.fold', this.parentNode).slideToggle();
$('>:first', this).toggleClass('open');
});
//默认情况下折叠
$("div.fold").css("display","none");
});

然后创建文件hexo-theme-next/layout/_custom/post-details.swig如下

1
2
3
4
{# hexo-theme-next/layout/_custom/post-details.swig
add to: themes/hexo-theme-next/layout/_scripts/pages/post-details.swig
#}
<script type="text/javascript" src="{{ url_for(theme.custom) }}/fold_action.js?v={{ version }}"></script>

并在themes/hexo-theme-next/layout/_scripts/pages/post-details.swig的末尾加上:

1
{% include '../../_custom/post-details.swig' %}

注意:还需修改主题下的_config.yml如下,即加入custom: custom(其实是配置了source目录下的文件夹)

1
2
3
4
5
# Assets
css: css
js: js
images: images
+custom: custom

样式修改

最后,修改hexo-theme-next/source/css/_custom/custom.styl配置风格:

1
2
3
4
5
6
7
8
9
10
11
// 代码折叠功能添加
.hider_title{
cursor: pointer;
color: #ef4a05;
}
.close:before{
content: "▼";
}
.open:before{
content: "▲";
}

使用方法

代码块折叠使用方法:

1
2
3
{% fold 点击显/隐内容 %}
something you want to fold, include code block.
{% endfold %}

实际显示效果:

点击显/隐内容

something you want to fold, include code block.

参考


----------- 本文结束啦感谢您阅读 -----------

赞赏一杯咖啡

欢迎关注我的其它发布渠道