【问题标题】:add CSS style to selectInput choices programatically以编程方式将 CSS 样式添加到 selectInput 选项
【发布时间】:2020-11-13 10:11:44
【问题描述】:

我正在编写一个闪亮的应用程序,并且我正在尝试根据条件更改 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)

【问题讨论】:

    标签: r shiny shinyjs


    【解决方案1】:

    您可以使用 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)
    

    【讨论】:

    • 非常感谢,我发现了一个非常肮脏的方法,但你的方法很棒,我编辑了你的答案,所以它可以做我想做的事情(根据变量在 selectInput 选项中使用颜色)
    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 2017-11-24
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多