首页 > 解决方案 > 如何在服务器端设置闪亮的小部件 css?

问题描述

我的目标是通过每次点击来更改 actionButton css,有没有一种方法可以在不使用 shinyBS 和 shinyjs 的情况下实现?

请参阅下面的最小可重现示例。

library(shiny)
shinyApp(
  ui = fluidPage(
    tags$style("#action{color:black;}"),
    actionButton("action", label = "Action")
  ),
  server = function(input, output) {
    observeEvent(input$action, {
      message(input$action %% 2)
      if (input$action %% 2) {
        tags$style("#action{color:red;}")
      } else {
        tags$style("#action{color:black;}")
      }
    })
  }
)

点击 1 红色

点击 2 黑色

点击 3 红色

点击 4 黑色

点击 5 红色

...

标签: javascriptcssrshinyshinydashboard

解决方案


一种 JavaScript 方式:

js <- "
function changeColor(button){
  var currentColor = button.style.color;
  var newColor = currentColor === 'red' ? 'black' : 'red';
  button.style.color = newColor;
}
"

ui <- basicPage(
  tags$head(tags$script(HTML(js))),
  actionButton(
    "btn", "Click me", style = "color: red;", 
    onclick = "changeColor(this)"
  )
)

server <- function(input, output, session){}

shinyApp(ui, server)

推荐阅读