首页 文章

如何查看闪亮的仪表板框是否从服务器端折叠

提问于
浏览
0

我正试图找到一种方法来检查Shiny Dashboard Box是否已折叠或展开 .

通过阅读@daattali在How to manually collapse a box in shiny dashboard中的精彩回复,我知道可以通过使用shinyjs包从服务器端折叠盒子,如下面的代码所示

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)

通过检查UI HTML我看到我的问题的答案可以通过访问图标类来解决(看它是fa fa-plus还是fa fa-minus),但我不知道如何做到这一点 .

任何帮助将不胜感激 .

干杯

1 回答

  • 1

    您可以创建一个新的输入,在用户折叠框时触发,具有以下内容:

    collapseInput <- function(inputId, boxId) {
      tags$script(
        sprintf(
          "$('#%s').closest('.box').on('hidden.bs.collapse', function () {Shiny.onInputChange('%s', true);})",
          boxId, inputId
        ),
        sprintf(
          "$('#%s').closest('.box').on('shown.bs.collapse', function () {Shiny.onInputChange('%s', false);})",
          boxId, inputId
        )
      )
    }
    

    以你为例:

    library(shiny)
    library(shinydashboard)
    library(shinyjs)
    
    jscode <- "
    shinyjs.collapse = function(boxid) {
    $('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
    }
    "
    collapseInput <- function(inputId, boxId) {
      tags$script(
        sprintf(
          "$('#%s').closest('.box').on('hidden.bs.collapse', function () {Shiny.onInputChange('%s', true);})",
          boxId, inputId
        ),
        sprintf(
          "$('#%s').closest('.box').on('shown.bs.collapse', function () {Shiny.onInputChange('%s', false);})",
          boxId, inputId
        )
      )
    }
    
    
    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")),
        collapseInput(inputId = "iscollapsebox1", boxId = "box1"),
        verbatimTextOutput(outputId = "res")
      )
    )
    
    server <- function(input, output) {
      observeEvent(input$bt1, {
        js$collapse("box1")
      })
      observeEvent(input$bt2, {
        js$collapse("box2")
      })
    
      output$res <- renderPrint({
        input$iscollapsebox1
      })
    }
    
    shinyApp(ui, server)
    

    如果需要,可以在函数 collapseInput 中通过 'collapse' / 'expanded' 更改 true / false .

相关问题