在 RMarkdown HTML 输出中使用内部链接

Use internal links in RMarkdown HTML output

我正在使用 R Studio 创建 Rmarkdown (.Rmd) 文档。 我试过了:

Jump to [Header 1](#anchor)

我想设置一个 link,这样当 reader 点击它时,他们会跳转到页面上的特定点。

假设我希望他们被引导到的点有一个 header“## Test”。

这是 HTML 文档的解决方案,使用 jQuery:

---
title: "Internal Links"
output: html_document
---

# First Section

## Second Section

### Third Section


<script type="text/javascript">
  // When the document is fully rendered...
  $(document).ready(function() {
    // ...select all header elements...
    $('h1, h2, h3, h4, h5').each(function() {
      // ...and add an id to them corresponding to their 'titles'
      $(this).attr('id', $(this).html());
    });
  });
</script>


<a href="#First Section">Go to first section</a><br>
<a href="#Second Section">Go to second section</a><br>
<a href="#Third Section">Go to third section</a>

正如评论所指出的,我们简单地 select 所有 header ,读出它们的内容(例如 "First Section")并添加属性 id 的值对应到每个header的具体内容。 现在你可以 link 到任何 header 使用 #HEADER (例如 #First Section)。


这当然可以扩展到您希望锚定的所有其他元素。因此,如果您想 link 到您的任何块,只需将此脚本添加到您的文档中:

<script type="text/javascript">
  $(document).ready(function() {
    $('pre.r').each(function(i) {
      $(this).attr('id', 'Chunk_' + i);
    });
  });
</script>

现在您可以通过使用 <a href="Chunk_i">My Chunk</a> link 到块,其中 i 从第一个块 0 到您的最后一个块 N文件.

Pandoc 支持 headers 的显式和隐式节引用;参见 the pandoc manual

  • 显式:您给 header ## Test {#test} 一个自定义名称,然后使用 link 语法引用它:see [the relevant section](#test).
  • implicit: headers 没有设置自定义名称的地方,比如## Test,仍然可以参考:See the section called [Test].

两种语法都应允许您单击 link 转到锚点,并且应该适用于大多数输出​​格式。 (仅使用 html 和 pdf 进行测试)。

---
output:  pdf_document
---

## A section

blah blah

## A second section with a custom identifier {#custom}

blah blah

## Links

You can use implicit references to refer to sections
you have not explicitly named, like this: 
see [A section]. 

You can use links to refere to sections with explicit
references, like this: see [the second section](#custom).