如何在bookdown中设置全局代码折叠默认隐藏所有代码
bookdown 全局代码默认隐藏解决方案
- 第一步:在你的bookdown项目根目录下新建
script.js文件,粘贴以下代码:
// 全局代码折叠切换逻辑 $(document).ready(function() { // 初始默认隐藏所有代码块 $('pre.sourceCode').parent().hide(); // 插入全局切换按钮 $('<button id="toggle-all-code" style="position: fixed; top: 10px; right: 20px; z-index: 999; padding: 6px 12px; border-radius: 4px; border: none; background: #2c3e50; color: white; cursor: pointer;">显示全部代码</button>').appendTo('body'); // 切换按钮点击逻辑 $('#toggle-all-code').click(function() { if ($(this).text() === '显示全部代码') { $('pre.sourceCode').parent().show(); $(this).text('隐藏全部代码'); } else { $('pre.sourceCode').parent().hide(); $(this).text('显示全部代码'); } }); // 保留单个代码块的折叠能力(可选) $('pre.sourceCode').each(function() { const toggleBtn = $('<span class="single-code-toggle" style="float: right; cursor: pointer; color: #3498db; font-size: 0.9em;">显示代码</span>'); $(this).before(toggleBtn); toggleBtn.click(function() { if ($(this).text() === '显示代码') { $(this).next('pre.sourceCode').parent().show(); $(this).text('隐藏代码'); } else { $(this).next('pre.sourceCode').parent().hide(); $(this).text('显示代码'); } }); }); });
- 第二步:修改项目下的
_output.yml配置,引入自定义JS文件(gitbook默认自带jquery无需额外引入):
bookdown::gitbook: includes: in_header: !expr paste0( '<script src="', rprojroot::find_rstudio_root_file(), '/script.js"></script>' ) config: toc: collapse: section
- 第三步:重新编译bookdown项目即可生效。编译后的文档默认所有代码块处于隐藏状态,右上角固定的全局切换按钮可一键控制所有代码的显示/隐藏,也支持单个代码块单独切换状态。
内容的提问来源于stack exchange,提问作者NewGraph
相关产品推荐
相关产品推荐

