写博客有时候需要添加的代码真的很多, 而我们又不想让它显示在网页上.

添加一个代码隐藏功能吧!

  首先, 你要明白不论添加一些什么功能, 无非是添加一些js插件实现.

1.自定义内置标签

  通过查看自定义标签的API, 发现主题自带标签脚本都会存放在themes/xxx/scripts/tag/xxx.js

首先, 我们要注册一个自己的代码隐藏内置标签fold.

新建fold.js(提取码: 0khu)文件, 路径(没有相应目录的自建)如图:

fold

内容:

One More Thing 👇
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});

2.消除渲染undefined问题

在scripts目录下添加一个tags.js(提取码: giom)文件, 内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
修复在 fold 标签里写 ```代码块```,最终会被渲染成 undefined 的问题
*/
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;
});

3.设置默认折叠代码

将下列代码复制到你的主题的JS(每个页面都会加载的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");
});

4.配置fold显示样式

将下述代码复制到你的主题样式文件里:

1
2
3
4
5
6
7
8
9
10
.hider_title{
font-family: "Microsoft Yahei";
cursor: pointer;
}
.close:after{
content: "▼";
}
.open:after{
content: "▲";
}

评论