有些时候经常会遇到博客中很长的代码段,占据半个甚至整个屏幕,此时就非常需要将代码段进行折叠,以此来缓解代码块影响阅读的问题。
配置走起!
配置步骤
- 取消注释
打开themes\next\_config.yml文件。
CTRL+F查找关键字“custom_file_path”(如果你使用的是VS-CODE编辑器)。
取消bodyEnd: source/_data/body-end.njk注释和style: source/_data/styles.styl注释。
折叠代码1 2 3 4 5 6 7 8 9 10 11
| custom_file_path: footer: source/_data/footer.swig bodyEnd: source/_data/body-end.njk variable: source/_data/variables.styl style: source/_data/styles.styl
|
- 按照
style的路径和bodyEnd的路径添加相应的文件,如果当前不存在此文件的话。如果已经存在的话,添加以下配置。
折叠代码1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| <script> document.addEventListener("DOMContentLoaded", function() { const tableContainers = document.querySelectorAll(".table-container");
tableContainers.forEach(function(tableContainer) { const spanCount = tableContainer.querySelectorAll("tbody > tr > td.code > pre > span").length;
if (spanCount >= 11) { const prevElement = tableContainer.previousElementSibling; let figcaption; let iElement; if (!prevElement || prevElement.tagName.toLowerCase() !== "figcaption") { figcaption = document.createElement("figcaption");
tableContainer.parentNode.insertBefore(figcaption, tableContainer); } else { figcaption = prevElement; }
iElement = document.createElement("i"); iElement.className = "fas fa-angle-down"; iElement.innerHTML = " "; figcaption.insertBefore(iElement, figcaption.firstChild);
iElement.addEventListener("click", function() { tableContainer.classList.toggle("code-hidden");
if (iElement.classList.contains("fa-angle-down")) { iElement.classList.remove("fa-angle-down"); iElement.classList.add("fa-angle-right"); } else { iElement.classList.remove("fa-angle-right"); iElement.classList.add("fa-angle-down"); } }); } }); }); </script>
|
PS:在代码的第11行,可以按照自己的需要进行设置,当代码超过多少行时,折叠代码的JS生效。
1 2 3 4
| /* 代码块隐藏 */ .code-hidden { display: none; }
|
1 2 3
| ```bash 折叠代码 /* some code */ ```
|
完成的效果就像添加JS代码的代码块一样。
补充
已经取消注释的文件对应的功能和教程链接。