以编程方式将 CSS 样式添加到 selectInput 选择

add CSS style to selectInput choices programatically

我正在编写一个闪亮的应用程序,我正在尝试根据条件更改 selectInput 中显示的选项的颜色。 我的意图是,如果选项的名称是“已安装”,则将其涂成绿色,如果不是,则涂成红色 我试过 shinyjs::addClass() 但失败了。

这是我目前得到的:

library(shiny)
library(shinyjs)

names <- c("A", "B", "C")
installed <- c("TRUE", "FALSE", "FALSE")

options <- data.frame(names, installed)


ui <- fluidPage(
  useShinyjs(),
  # inlineCSS("#someId .selectize-dropdown-content > .option { color: red; }"),
  # inlineCSS("#someId .selectize-input { color: red; }"),
  inlineCSS(".red {color:red;}"),
  inlineCSS(".green {color: green;}"),
  selectInput("apkgs", "Select a package", choices = options$names),
)

server <- function(input, output, session) {
  observe({
    if(input$apkgs %in% installed) {
      addClass(selector="input.apkgs", class="green")
    } else {
      addClass(selector="input.apkgs", class="red")
    }
  })
}

shinyApp(ui, server)

您可以使用 renderUI:

制作动态 CSS 样式
library(shiny)

names <- c("A", "B", "C")
options <- data.frame(names)

cssTemplate <- function(color){
  sprintf(
    ".selectize-dropdown-content > .option,
     .selectize-input > .item 
     {
       color: %s; 
     }",
    color
  )
}
  
ui <- fluidPage(
  tags$head(
    uiOutput("css")
  ),
  selectInput("apkgs", "Select a package", choices = options$names),
 )
 
server <- function(input, output, session) {
   
  output[["css"]] <- renderUI({
    color <- ifelse(input$apkgs == "A", "green", "red")
    tags$style(HTML(cssTemplate(color)))
  })
  
}

shinyApp(ui, server)

OP 编辑​​

library(shiny)

names <- c("A", "B", "C")
installed <- c(TRUE, FALSE, FALSE)
options <- data.frame(names, installed)


ui <- fluidPage(
  tags$head(
    uiOutput("css")
  ),
  
  div(id="algo",
      selectInput("apkgs", "Select a package", choices = options$names)
      )
)

server <- function(input, output, session) {
  output$css <- renderUI({
    tags$style(
      HTML(unlist(
        lapply(names, function(x){
          if(options[options$names==x,]$installed) {
            sprintf("#algo .selectize-dropdown-content > .option[data-value='%s'] { color: green; }", x)
          } else {
            sprintf("#algo .selectize-dropdown-content > .option[data-value='%s'] { color: red; }", x)
          }
        })
        )
      )
    )
  })
}


shinyApp(ui, server)