Shinydashboard - 根据所选标签更改背景

时间:2018-03-19 08:12:33

标签: css r shiny shiny-server shinydashboard

我正在使用Shinydashboard包创建仪表板,我需要根据所选的Tab更改背景颜色。我已经尝试了以下代码,但它没有按预期工作。

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)

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是渲染样式标记,具体取决于所选标签。请注意,为了这样做,sidebarmenu需要id。下面是一个工作示例,希望这有帮助!

enter image description here

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)
相关问题