2017-04-21 93 views
1

我正在根據用戶輸入添加樣式標籤。根據用戶選擇的單選按鈕,selectInput的邊框顏色會發生變化。在下面的示例代碼中,如果用戶選擇單選按鈕中的「錯誤」,並且如果用戶選擇「無錯誤」,則將其設置回灰色(默認顏色),則將顏色設置爲紅色。刪除從服務器端添加的樣式標籤

我面臨的問題是,我每次用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) 

回答

3

你需要做的是有一個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) 
+0

我不希望我的'selectInput'顯示錯誤。只是我選擇的那個。這只是一個示例代碼,我的實際應用程序有很多'selectInput'。我沒有在我的問題中說清楚,這段代碼當然可以回答我的問題。您是否知道一種方法來爲某個'selectInput'添加樣式並將其刪除? – SBista

+0

'addCssClass'確實有'id'參數。不幸的是,它不適用於'select'輸入,因爲id附加在DOM的隱藏元素上。您可以使用您已有的選擇器。更新答案 – GGamba

+0

謝謝。這正是我想要的。 – SBista