[关闭]
@MrXiao 2018-12-06T05:54:10.000000Z 字数 1828 阅读 1545

Next主题添加内容折叠

博客


当有大段的代码直接展示在页面时,看起来臃肿且不便于观看,此时将代码折叠式最好的选择。下面是在Hexo的Next主题上添加折叠功能。

1、在main.js中添加折叠js

Next主题的主要js位于 themes/next/source/js/src/post-details.js,在下面添加一下代码段:

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

2、自定义内建标签

在主题scripts下添加一个tags.js,位于themes/next/scripts/tags.js

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

再继续添加一个fold.js,位于themes/next/scripts/fold.js

  1. /* global hexo */
  2. // Usage: {% fold ???? %} Something {% endfold %}
  3. function fold (args, content) {
  4. var text = args[0];
  5. if(!text) text = "点击显/隐";
  6. 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>';
  7. }
  8. hexo.extend.tag.register('fold', fold, {ends: true});

3、添加自定义样式

位于themes/next/source/css/_custom/custom.styl

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

4、使用

在我们需要折叠的地方前后添加便签,示例用法:

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

5、参考

Hexo next博客添加折叠块功能添加折叠代码块
Next主题实现内容折叠
jQuery 实现内容折叠功能

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注