ShinyDashboard-根据所选选项卡更改背景
我正在使用Shinydashboard包创建仪表板,其中我需要根据选定的选项卡更改背景颜色。我已尝试以下代码,但它不能按预期工作。
library(shiny)
library(shinydashboard)
library(dplyr)
ui <- dashboardPage(dashboardHeader(dropdownMenuOutput("notificationMenu")),
dashboardSidebar(sidebarMenu(menuItem("Page 1", tabName = "page1"),
menuItem("Page 2", tabName = "page2"))),
dashboardBody(tags$style(".content {background-color: #f7f7f7;
.content-wrapper .tab-pane .shiny-tab-page1 {background-color: #000000;
}
"),
tabItems(
tabItem(tabName = "page1", h4("This is Page 1")),
tabItem(tabName = "page2",
textInput("text", "Enter News:", "New News."),
actionButton("save", "Save")))))
server <- function(input, output, session){
raw_news <- reactiveValues()
# Intial Header News: 1 Message from Admin
raw_news$news <- data_frame(from = "Admin", text = "this is a message")
# The notifications in header
output$notificationMenu <- renderMenu({
raw_news <- raw_news$news
dropdownMenu(
messageItem(raw_news$from[1], raw_news$text[1])
)
})
# save a new notification
observeEvent(input$save, {
raw_news$news <- data.frame(from = "User", text = input$text)
})
}
shinyApp(ui = ui, server = server)
如有任何帮助,将不胜感激。
解决方案
一种可能的解决方案是根据选定的选项卡呈现样式标记。请注意,为了做到这一点,侧栏菜单需要id
。以下是一个工作示例,希望对您有所帮助!
library(shiny)
library(shinydashboard)
ui <- dashboardPage(dashboardHeader(dropdownMenuOutput("notificationMenu")),
dashboardSidebar(sidebarMenu(id='sidebar',
menuItem("Page 1", tabName = "page1"),
menuItem("Page 2", tabName = "page2")),
uiOutput('style_tag')),
dashboardBody(
tabItems(
tabItem(tabName = "page1", h4("Blue!",style='color:white')),
tabItem(tabName = "page2", h4('Red!'))
))
)
server <- function(input, output, session){
output$style_tag <- renderUI({
if(input$sidebar=='page1')
return(tags$head(tags$style(HTML('.content-wrapper {background-color:blue;}'))))
if(input$sidebar=='page2')
return(tags$head(tags$style(HTML('.content-wrapper {background-color:red;}'))))
})
}
shinyApp(ui = ui, server = server)
相关文章