我希望根据用户的输入来更改Shiny应用程序中文本的颜色。这是一个简单的例子。这基本上是正确的方法吗?如果我对css进行硬编码,它将起作用。例如,如果我更改:
div(style = css_stub,
到
div(style = "inline-block; red;",
文字颜色改变。请说明如何以编程方式更改Shiny应用程序中的CSS。
library(shiny)
css_stub <- paste0("'", "inline-block; color:black;", "'")
ui <- fluidPage(
titlePanel("Color Test"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "colors",
label = "Choose a color:",
choices = c("red", "blue"))
),
mainPanel(
div(style = css_stub,
textOutput("text_out"))
)
)
)
server <- function(input, output) {
observeEvent(input$colors, {
if (input$colors == "red") {
css_stub <- paste0("'", "inline-block; color:red;", "'")
output$text_out <- renderText({"hello - red"})
} else {
css_stub <- paste0("'", "inline-block; color:blue;", "'")
output$text_out <- renderText({"hello - blue"})
}
})
}
shinyApp(ui = ui, server = server)
答案 0 :(得分:2)
我将为每个类定义类和样式,然后使用shinyjs库添加/删除类。
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$style(HTML("
div.red { color: red; }
div.blue { color: blue; }
"))
),
titlePanel("Color Test"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "colors",
label = "Choose a color:",
choices = c("red", "blue"))
),
mainPanel(
div(id="color_change", style = "inline-block; ",
textOutput("text_out"))
)
)
)
server <- function(input, output) {
observeEvent(input$colors, {
color_to_set <- input$colors
color_to_unset <- setdiff(c("red", "blue"), color_to_set)
shinyjs::addClass("color_change", color_to_set)
for (col in color_to_unset) shinyjs::removeClass("color_change", col)
})
output$text_out = renderText(paste("Hello -", input$colors))
}
shinyApp(ui = ui, server = server)