R & Knitr html output: Create collapsing and expanding header

余生颓废 提交于 2020-01-01 05:07:06

问题


Use case

I use R and Knitr a lot to produce long html reports. The reports contain headers by using the markdown # syntax. These headers give good orientation for the reader's navigation...

Problem

... but the reports sometimes get very long. Scrolling from beginning to the end take very long time. Readers of the reports get annoyed seeing all the report content before reaching the relevant parts.

Question

Is there a way to implement in Knitr a collapsing and expanding header element?

Requirements

  • By default the header shall be collapsed. Only by clicking the contents below the header shall expand. This would tremendously help to keep the reports small in appearance and facilitate easy and fast navigation.
  • In order to give the reader feedback of the state the header it shall represent it's state. I recommend something along the mechanism used in Wikipedia (see image above).

回答1:


You can make elements collapse using Javascript. The jQuery JavaScript framework makes this reasonably easy via the hide and show methods.

In the folder that contains your Rmd template, create a subfolder named script and save the jQuery file in it. (Doesn't have to be there, but that's a reasonably standard location.)

Add this code near the top of your Rmd file.

<script type="text/javascript" language="javascript" src="script/jquery-1.10.2.min.js">
</script>

For Markdown, the closing tag needs to be on a separate line.

Alternatively, if your report is mostly going to be read on machines where there is internet access, you can should use a Google-hosted version of jQuery.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" >
</script>

Then add another script block for your collapsing logic. The exact implementation is up to you; there are lots of examples on the internet.

The key to making your collapsing/expanding logic simple is to make sure that the elements you are manipulating have a consistent class (or a pattern to their ids).



来源:https://stackoverflow.com/questions/20699178/r-knitr-html-output-create-collapsing-and-expanding-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!