You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在bookdown中实现代码块交叉引用 获得类似图表公式的跳转效果

完善方案实现代码块交叉引用

你可以按照以下步骤补充配置,实现锚点跳转功能:

步骤1:修改原有CSS样式

首先删除你现有CSS中.demor::after相关的规则,替换为以下样式,适配后续插入的锚点编号:

.book .book-body .page-wrapper .page-inner section.normal {
  counter-reset: counter-rchunks;
}

.book .book-body .page-wrapper .page-inner section.normal div.section div.sourceCode {
  padding-right: 5em;
  position: relative;
}

.book .book-body .page-wrapper .page-inner section.normal div.section div.sourceCode pre.demor {
  counter-increment: counter-rchunks;
  overflow: visible;
}

/* 新增编号锚点样式 */
.code-chunk-number {
  position: absolute;
  right: 1em;
  bottom: 0.5em;
  color: rgb(48, 63, 159);
  text-decoration: none;
}
.code-chunk-number:hover {
  text-decoration: underline;
}

步骤2:添加自动生成锚点的JS脚本

在你的bookdown项目中新增一个inject.html文件,写入以下JS代码:

<script>
document.addEventListener('DOMContentLoaded', function() {
  // 遍历所有带demor类的代码块
  const demorChunks = document.querySelectorAll('pre.demor');
  demorChunks.forEach((chunk, index) => {
    const chunkNum = index + 1;
    // 如果代码块没有设置id,自动生成唯一id
    let chunkId = chunk.id;
    if (!chunkId) {
      chunkId = `code-chunk-${chunkNum}`;
      chunk.id = chunkId;
    }
    // 插入带锚点的编号标签
    const numberTag = document.createElement('a');
    numberTag.href = `#${chunkId}`;
    numberTag.className = 'code-chunk-number';
    numberTag.textContent = `[${chunkNum}]`;
    chunk.parentNode.appendChild(numberTag);
  })
})
</script>

然后在_bookdown.yml配置文件中添加配置,让编译时自动注入这段脚本:

output:
  bookdown::gitbook:
    includes:
      in_header: inject.html

步骤3:代码块配置与正文引用

代码块配置

如果需要自定义代码块的ID(方便记忆引用),可以在代码块头部添加attr.source参数设置id:

```{r class.source = "demor", attr.source = "id='code-cars-demo'"}
cars |>
  dplyr::slice_head(n = 3)
#### 正文引用
直接在正文中使用Markdown链接语法跳转即可,比如:

如代码块1所示

如果是自动生成的ID,直接引用`#code-chunk-1`、`#code-chunk-2`对应顺序的代码块即可。

内容的提问来源于stack exchange,提问作者chunyun
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:39:00