我以前从未尝试过使用盒子,所以请记住,我的回答可能非常狭隘。但我快速浏览了一下,看起来只是在盒子上设置“折叠盒”类实际上并没有使盒子折叠。因此,我的下一个想法是以编程方式实际单击折叠按钮。
正如您所说,没有与该框关联的标识符,因此我的解决方案是id
在box
. 我最初期望它是盒子的 id,但看起来这个 id 是给盒子内的一个元素的。没问题 - 这只是意味着为了选择折叠按钮,我们需要获取 id,查找 DOM 树找到 box 元素,然后再向下查找 DOM 树找到按钮。
我希望我所说的一切都是有道理的。即使没有,这段代码应该仍然可以工作,并且希望能让事情变得更清楚:)
library(shiny)
library(shinydashboard)
library(shinyjs)
jscode <- "
shinyjs.collapse = function(boxid) {
$('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
}
"
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
useShinyjs(),
extendShinyjs(text = jscode),
actionButton("bt1", "Collapse box1"),
actionButton("bt2", "Collapse box2"),
br(), br(),
box(id = "box1", collapsible = TRUE, p("Box 1")),
box(id = "box2", collapsible = TRUE, p("Box 2"))
)
)
server <- function(input, output) {
observeEvent(input$bt1, {
js$collapse("box1")
})
observeEvent(input$bt2, {
js$collapse("box2")
})
}
shinyApp(ui, server)