用shinyjs改变shinydashboard框的样式
Posted
技术标签:
【中文标题】用shinyjs改变shinydashboard框的样式【英文标题】:Change style of shinydashboard box with shinyjs 【发布时间】:2021-06-13 19:11:37 【问题描述】:我正在尝试根据用户所在的选项卡更改闪亮仪表板框的颜色。 为此,我从 tabsetPanel 获取输入值,并尝试使用 shinyjs 更改 box-header 类的 css。不幸的是,我的试验都没有成功。这是一个可重现的示例(颜色尚未适应选项卡,但我会在第二部分中这样做)
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 调用之间的所有组合,但都失败了。
【问题讨论】:
【参考方案1】:您只是在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)
【讨论】:
我们不需要运行多个runjs。多行可以包裹在一个runjs中【参考方案2】: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")
)
)
)
【讨论】:
以上是关于用shinyjs改变shinydashboard框的样式的主要内容,如果未能解决你的问题,请参考以下文章