使用 shinyjs 更改 shinydashboard 框的样式

Change style of shinydashboard box with shinyjs

我正在尝试根据用户所在的选项卡更改 shinydashboard 框的颜色。 为此,我从 tabsetPanel 获取输入值,并尝试使用 shinyjs 更改 box-header class 的 css。不幸的是 none 我的试验成功了。这是一个可重现的例子(颜色还没有适应标签,但我会在第二部分做)

library(shiny)
ui <- fluidPage(
  shinyWidgets::useShinydashboard(),
  tabsetPanel(
    id = "mytab",
    tabPanel("First",
             shinydashboard::box(status = "primary",
                                 title = "mybox",
                                 solidHeader = TRUE, collapsible = TRUE,
                                 sliderInput("orders", "Orders", min = 1, max = 2000, value = 650)
                                 )),
  tabPanel("Second", p("Second tab"))))

server <- function(input, output) {
  observeEvent(input$mytab,{
    shinyjs::runjs("$('.box-header').css('background', 'red');")
    shinyjs::runjs("$('.box.box-solid.box-primary > .box-header').attr('style', 'background:red !important');")
  })
}
shinyApp(ui = ui, server = server)

我尝试了第一次和第二次调用 runjs 之间的所有组合,但都失败了。

您刚刚在 ui 中缺少 useShinyjs()。试试这个

library(shiny)
ui <- fluidPage(
  useShinyjs(),
  shinyWidgets::useShinydashboard(),
  #tabBox( id = "mytab", width=6, title = "My Test Plot",
  tabsetPanel(id = "mytab",
    tabPanel("First", value="tab1",
             shinydashboard::box(status = "primary",
                                 title = "mybox",
                                 solidHeader = TRUE, collapsible = TRUE,
                                 sliderInput("orders", "Orders", min = 1, max = 2000, value = 650)
             )),
    tabPanel("Second", value="tab2", p("Second tab"),
             shinydashboard::box(status = "warning",
                                 title = "mybox",
                                 solidHeader = TRUE, collapsible = TRUE,
                                 sliderInput("orders2", "Orders", min = 1, max = 2000, value = 950)
             ))
    )
  )

server <- function(input, output) {
  observeEvent(input$mytab,{
    if (input$mytab=="tab1"){
      shinyjs::runjs("$('.box-header').css('background', 'red');")
      shinyjs::runjs("$('.box.box-solid.box-primary > .box-header').attr('style', 'background:red !important');")
    } else if (input$mytab=="tab2"){
      shinyjs::runjs("$('.box-header').css('background', 'blue');")
      shinyjs::runjs("$('.box.box-solid.box-primary > .box-header').attr('style', 'background:blue !important');")
    }
    
  })
}
shinyApp(ui = ui, server = server)

https://rstudio.github.io/shinydashboard/appearance.html#css

    ## ui.R ##
dashboardPage(
  dashboardHeader(title = "Custom font"),
  dashboardSidebar(),
  dashboardBody(
    tags$head(
      tags$link(rel = "stylesheet", type = "text/css", href = "custom.css")
    )
  )
)