gpt4 book ai didi

r - 以编程方式更改 Shiny 脚本中的 css

转载 作者:行者123 更新时间:2023-12-02 03:29:21 25 4
gpt4 key购买 nike

我希望根据用户的输入更改 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)

最佳答案

我将为每个定义类和样式,然后使用 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)

关于r - 以编程方式更改 Shiny 脚本中的 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52286069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com