Hexo博客搭建及优化(二):添加代码折叠功能

添加代码折叠功能

代码折叠效果展示

点击显/隐
1
2
def function(arg):
pass

在POST主文件中添加JS判断代码

/themes/next/source/js/src/post-details.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","open");
});

定义内建标签

/themes/next/scripts/中新建文件 tags.js并添加如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
@haohuawu
修复 Nunjucks 的 tag 里写 ```代码块```,最终都会渲染成 undefined 的问题
https://github.com/hexojs/hexo/issues/2400
*/
const rEscapeContent = /<escape(?:[^>]*)>([\s\S]*?)<\/escape>/g;
const placeholder = '\uFFFD';
const rPlaceholder = /(?:<|&lt;)\!--\uFFFD(\d+)--(?:>|&gt;)/g;
const cache = [];
function escapeContent(str) {
return '<!--' + placeholder + (cache.push(str) - 1) + '-->';
}
hexo.extend.filter.register('before_post_render', function(data) {
data.content = data.content.replace(rEscapeContent, function(match, content) {
return escapeContent(content);
});
return data;
});
hexo.extend.filter.register('after_post_render', function(data) {
data.content = data.content.replace(rPlaceholder, function() {
return cache[arguments[1]];
});
return data;
});

在同一目录下新建文件fold.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});

添加折叠功能样式

/themes/next/soure/css/_custom/custom.styl添加如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Custom styles.
.hider_title{
font-family: "Microsoft Yahei";
cursor: pointer;
}
.close:after{
content: "▼";
}
.open:after{
content: "▲";
}

.feed-link a {
display: inline-block;
}

使用方法

1
2
3
{% fold %}
你需要折叠的内容
{% endfold %}

参考

0%