选中时突出显示R闪亮按钮的边框或颜色

时间:2018-06-21 10:06:54

标签: r button shiny shinydashboard highlighting

有人知道选中按钮时如何突出显示边框或颜色吗?

请在下面找到可复制的示例

library(shiny)

ui <- fluidPage(
  actionButton(inputId = "button1", label = "Select red"),
  actionButton(inputId = "button2", label = "Select blue"),
  plotOutput("distPlot")
)


server <- function(input, output) {
    r <- reactiveValues(my_color = "green")

    output$distPlot <- renderPlot({
      x <- faithful[, 2]
      bins <- seq(min(x), max(x))
      hist(x, breaks = bins, col = r$my_color)
    })

   observeEvent(input$button1, {
      r$my_color <- "red"
    })

  observeEvent(input$button2, {
    r$my_color <- "blue"
   })
}

shinyApp(ui = ui, server = server)

这是上面的代码所得到的:

enter image description here

这就是当我选择“选择红色”按钮时我想得到的(请注意,当选择按钮时,它应该突出显示另一个):

enter image description here

如果不可能,是否存在一种在选择按钮时更改按钮颜色的方法?

预先感谢

1 个答案:

答案 0 :(得分:4)

您可以使用shinyjs包在按钮上添加/删除CSS类。在这里,我使用Bootstrap中的btn-primary类将按钮设置为蓝色,但是您也可以添加自己的样式。

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  actionButton(inputId = "button1", label = "Select red"),
  actionButton(inputId = "button2", label = "Select blue"),
  plotOutput("distPlot")
)


server <- function(input, output) {
  r <- reactiveValues(my_color = "green")

  output$distPlot <- renderPlot({
    x <- faithful[, 2]
    bins <- seq(min(x), max(x))
    hist(x, breaks = bins, col = r$my_color)
  })

  observeEvent(input$button1, {
    removeClass("button2", "btn-primary")
    addClass("button1", "btn-primary")
    r$my_color <- "red"
  })

  observeEvent(input$button2, {
    removeClass("button1", "btn-primary")
    addClass("button2", "btn-primary")
    r$my_color <- "blue"
  })
}

shinyApp(ui = ui, server = server)

Result