使用rshiny变量更改背景颜色



我试图在rshiny中创建一个框,它将具有输入变量设置的背景颜色。我创建了一个输出:

mainPanel(
tags$div(uiOutput("image", align = "right"), h2(textOutput("text")), 
div(textOutput("text2"),div(style = "width: 5px;"), "w",div(style = "width: 5px;"), textOutput("text3"), style = "display: flex"),
div("tel. ", div(style = "width: 5px;"), textOutput("num"), style = "display: flex"),
div("e-mail: ", div(style = "width: 5px;"), textOutput("text4"), style = "display: flex"),
style= "width: 800px; height: 400px;color: black; font-size:15px;
border: 5px solid white; padding: 15px; margin: 20px", class = "test")
)

现在我想修改背景颜色,输入如下:

eventReactive(input$kolor, {
if(input$kolor == 1)
{
HTML('<style type="text/css">
.test { background-color: white; }
</style>')

}
else if(input$kolor == 2)
{
HTML('<style type="text/css">
.test { background-color: green; }
</style>')
}
else if(input$kolor == 3)
{
HTML('<style type="text/css">
.test { background-color: blue; }
</style>')
}
})

不幸的是,当我改变输入变量时,什么也没有发生。有什么建议吗?

我们可以使用renderUI来实现这一点:

library(shiny)
ui <- fluidPage(titlePanel("Hello Shiny!"),
sidebarLayout(sidebarPanel(
selectInput(
inputId = "color",
label = "Color",
choices = c("white", "green", "blue")
)
),
mainPanel(uiOutput("mydiv"))))
server <- function(input, output, session) {
output$mydiv <- renderUI({
div(
"background-color test",
width = "100px",
height = "100px",
style = sprintf("background-color:%s;", input$color)
)
})
}
shinyApp(ui, server)

或者我们可以使用shinyjs::runjs:

library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "kolor",
label = "color",
choices = setNames(c("white", "green", "blue"), 1:3)
)
),
mainPanel(
tags$div(uiOutput("image", align = "right"), h2(textOutput("text")), 
div(textOutput("text2"),div(style = "width: 5px;"), "w",div(style = "width: 5px;"), textOutput("text3"), style = "display: flex"),
div("tel. ", div(style = "width: 5px;"), textOutput("num"), style = "display: flex"),
div("e-mail: ", div(style = "width: 5px;"), textOutput("text4"), style = "display: flex"),
style= "width: 800px; height: 400px;color: black; font-size:15px;
border: 5px solid white; padding: 15px; margin: 20px", class = "test", id = "testid")
)
)
)
server <- function(input, output, session) {
observeEvent(input$kolor, {
runjs(sprintf("document.getElementById('testid').style.backgroundColor = '%s';", input$kolor))
})
}
shinyApp(ui, server)

最新更新