删除从服务器端添加的样式标记

时间:2017-04-21 05:31:56

标签: r shiny

我根据用户输入添加样式标记。根据用户选择的单选按钮,selectInput的边框颜色会发生变化。在下面的示例代码中,如果用户选择"错误"我将颜色设置为红色。在radiobutton中,如果用户选择" No Error"我将其设置为灰色(默认颜色)。

我面临的问题是每次renderUI使用这些标签时,样式标签都会被添加到html头部。理想情况下,我想要删除我之前添加的样式标记。有没有办法做到这一点?

以下是我目前使用的代码:

library(shiny)

  ui <- fluidPage(

    uiOutput("Border_Arg"),

    radioButtons("RBtn", "Choices", choices = c("Error", "No Error")),

    selectInput("Select1", "Option1", choices = NULL)

  )


  server <- function(input, output){

    output$Border_Arg <- renderUI({

      if(input$RBtn == "Error"){
        tagList(
          tags$head(tags$style(HTML("#Select1 ~ .selectize-control.single .selectize-input {border: 1px solid red;}")))
          ) 
      }else if(input$RBtn == "No Error"){
        #Here, instead of setting the style to default value I would like to remove the style that was previously added
        tagList(
        tags$head(tags$style(HTML("#Select1 ~ .selectize-control.single .selectize-input {border: 1px solid #cccccc;}")))
        ) 
      }

    })
  }


  shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:4)

你需要做的是有一个CSS类来添加你想要的样式,然后添加和删除元素上的类。

我们可以使用shinyjs包来帮助解决这个问题:

library(shiny)
library(shinyjs)

ui <- fluidPage(

    useShinyjs(),
    inlineCSS(list(.error = "border: 2px solid red")),

    uiOutput("Border_Arg"),

    radioButtons("RBtn", "Choices", choices = c("Error", "No Error")),

    selectInput("Select1", "Option1", choices = LETTERS[1:4])

)


server <- function(input, output){

    output$Border_Arg <- renderUI({

        if(input$RBtn == "Error"){
          addCssClass(class = 'error', selector = '#Select1 ~ .selectize-control.single .selectize-input')
        }else if(input$RBtn == "No Error"){
            removeCssClass(class = 'error', selector = '#Select1 ~ .selectize-control.single .selectize-input')
        }

    })
}


shinyApp(ui = ui, server = server)