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

如何在Shiny应用中实现R Markdown式可跳转目录体验

要实现类似R Markdown的浮动目录跳转效果,你可以通过给内容块定义唯一ID、绑定点击滚动事件来实现,修改后的完整可运行代码如下:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      # 目录项,绑定对应跳转目标的ID
      menuItem("绘图区域", tabName = "plot", 
               `data-target` = "#section_plot", 
               class = "toc-link"),
      menuItem("滑块控件", tabName = "plot", 
               `data-target` = "#section_slider", 
               class = "toc-link")
    )
  ),
  dashboardBody(
    # 引入平滑滚动JS
    tags$script(HTML("
      $(document).on('click', '.toc-link', function(e) {
        // 阻止默认的tab切换跳转行为
        e.preventDefault();
        // 获取目标元素ID
        const targetId = $(this).data('target');
        // 平滑滚动到目标位置
        $('html, body').animate({
          scrollTop: $(targetId).offset().top
        }, 400);
      });
    ")),
    tabItems(
      tabItem(
        tabName = "plot",
        # 给绘图区域加唯一ID
        fluidRow(id = "section_plot",
          box(plotOutput("plot1", height = 250)),
        ),
        fluidRow(verbatimTextOutput('longtext')),
        # 给滑块区域加唯一ID
        fluidRow(id = "section_slider",
          box(
            title = "slider",
            sliderInput("slider", "Number of observations:", 1, 100, 50)
          )
        )
      )
    )
  )
)

server <- function(input, output) {
  output$plot1 <- renderPlot({hist(rnorm(500)[seq_len(input$slider)])})
  
  output$longtext <- renderText({paste0(rep('blah', 100), collapse = '\n')})
}

shinyApp(ui, server)

运行代码后,点击侧边栏的目录项就会平滑滚动到对应内容位置,和R Markdown开启toc: true、toc_float: true的表现一致。如果需要实现跨tab的跳转逻辑,只需要在JS代码中补充先切换到对应tab再滚动的逻辑即可。

内容的提问来源于stack exchange,提问作者student

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:45:01