R Shiny应用Story标签页实现顶部可点击跳转目录方法咨询
Shiny Story标签页可点击跳转目录实现方案
不需要引入第三方扩展包,直接用原生HTML锚点能力就能实现和Word一致的点击目录跳转对应章节的效果,修改步骤如下:
- 给每个需要跳转的章节标题绑定唯一ID,作为跳转的目标锚点
- 在Story标签页的最顶部插入目录区块,每个目录项用链接指向对应锚点ID
- (可选)加少量CSS实现平滑滚动、目录样式优化,体验更接近Word目录
具体修改后的完整代码
tabPanel("Story", # 顶部插入可点击目录 fluidRow( column(width=2), column( width=6, offset=1, style="background-color:#f8f9fa;border-radius:10px;padding:15px;margin-bottom:20px;", h4("目录", style="font-family:Georgia;margin-top:0;"), tags$ul( style="list-style-type:none;padding-left:0;line-height:2;", tags$li(tags$a("Introduction", href="#intro", style="color:#2c3e50;text-decoration:none;")), tags$li(tags$a("Chapter I", href="#chapter1", style="color:#2c3e50;text-decoration:none;")), tags$li(tags$a("Chapter II", href="#chapter2", style="color:#2c3e50;text-decoration:none;")) ), # 加平滑滚动效果 tags$style("html {scroll-behavior: smooth;} a:hover {text-decoration:underline !important;}") ) ), # 原有内容,给每个章节标题加id作为锚点 fluidRow(column(width=2), column( # 给Introduction加id="intro" h3(p(tags$em("Introduction"),style="color:black;text-align:left; font-family: Georgia; font-size: 20px"), id="intro"), width=6,offset=1,style="background-color:white;border-radius: 10px")), fluidRow(column(width=2), column( h4(p("This is a short story about nature")), width=6,offset=1, style="background-color:white;border-radius: 10px")), fluidRow(column(width=2), column( # 给Chapter I加id="chapter1" h3(p(tags$em("Chapter I"),style="color:black;text-align:left; font-family: Georgia; font-size: 20px"), id="chapter1"), width=6,offset=1,style="background-color:white;border-radius: 10px")), fluidRow(column(width=2), column( h4(p("In this chapter we present the background of the story")), width=6,offset=1, style="background-color:white;border-radius: 10px")), fluidRow(column(width=2), column( # 给Chapter II加id="chapter2" h3(p(tags$em("Chapter II"),style="color:black;text-align:left; font-family: Georgia; font-size: 20px"), id="chapter2"), width=6,offset=1,style="background-color:white;border-radius: 10px")), fluidRow(column(width=2), column( h4(p("This chapter is about the main protagonists")), width=6,offset=1, style="background-color:white;border-radius: 10px")) )
效果说明
- 打开Story标签页后最顶部会显示浅灰色背景的目录块
- 鼠标悬浮在目录项上会显示下划线,点击后页面会平滑滚动到对应章节的标题位置
- 如果后续新增章节,只要给新章节标题加新的唯一id,再在目录的
tags$ul里新增对应<a>标签的目录项即可,逻辑完全一致。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

