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

实现Shiny Box点击标题栏任意位置展开/折叠功能

Got it, let's fix this so clicking anywhere on the box title bar triggers expand/collapse, not just the tiny +/- icon. Here's a straightforward solution using a bit of custom JavaScript alongside your Shiny code:

Modified Code with Clickable Title Bar

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    # Your target box with an optional ID (for targeting specific boxes if needed)
    box(
      title = "Histogram box title",
      status = "primary",
      solidHeader = TRUE,
      collapsible = TRUE,
      plotOutput("histPlot"),
      id = "clickable_hist_box" # Optional ID to target only this box
    ),
    
    # Custom JS to make title bars clickable
    tags$script(HTML("
      $(document).ready(function() {
        // Option 1: Make ALL collapsible box title bars clickable
        // $('.box.collapsible .box-header').on('click', function(e) {
        
        // Option 2: Target ONLY the box with ID 'clickable_hist_box'
        $('#clickable_hist_box .box-header').on('click', function(e) {
          // Skip if we clicked the actual +/- icon (avoids double-triggering)
          if (!$(e.target).hasClass('btn-box-tool') && !$(e.target).hasClass('fa')) {
            // Simulate a click on the collapse button
            $(this).find('.btn-box-tool').trigger('click');
          }
        });
      });
    "))
  )
)

server <- function(input, output) {
  output$histPlot <- renderPlot({
    hist(rnorm(100))
  })
}

shinyApp(ui, server)

How This Works:

  • We use jQuery to listen for clicks on the box's title bar (.box-header element)
  • We add a check to ignore clicks directly on the +/- icon itself—this prevents the action from firing twice (once from your click, once from the icon's native behavior)
  • When a valid click is detected, we programmatically trigger a click on the hidden collapse button (.btn-box-tool) that Shiny uses under the hood for expand/collapse

Choose Your Targeting:

  • Use Option 1 if you want every collapsible box in your app to have clickable title bars
  • Use Option 2 if you only want this behavior for specific boxes (just update the ID to match your box's id parameter)

This should work seamlessly with your existing Shiny setup without breaking any other functionality!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:31:10