【问题标题】:Change CSS properties based on shiny input根据闪亮的输入更改 CSS 属性
【发布时间】:2021-01-05 19:24:12
【问题描述】:

在我的应用中,CSS 属性位于一个单独的文件中,并通过 includeCSS('./www/styles.css') 包含在 UI 中。

是否可以根据输入的值动态更改 font-family 属性?

例如用户界面包含:

selectInput(inputId = 'selected_language', label = 'Choose language', choices = c('lao', 'english'), selected = 'english')

如果选择“lao”,则使用body { font-family: Phetsarath OT; },如果选择“english”,则使用body { font-family: Arial, Helvetica, sans-serif; }

【问题讨论】:

    标签: css r shiny


    【解决方案1】:

    您可以将 css 部分包含在 tags$style 中,并将其放在服务器端的 renderUI() 中。

    最简单的方法是将其余的 css 也放在服务器端,但您也可以从 styles.css 文件中读取,见下文。

    可重现的例子:

    library(shiny)
    
    # Simulating a styles.css file
    css_content <- "
    h4 {
      font-family: 'Lobster', cursive;
      font-weight: 500;
      line-height: 1.1;
      color: #48ca3b;
    }
    "
    
    writeLines(text = css_content, con = "styles.css")
    
    css <- readLines(con = "styles.css") %>% 
      paste(collapse = "\n")
    
    
    ui <- fluidPage(
      selectInput(inputId = 'selected_language', label = 'lang', choices = c('lao', 'english'), selected = 'english'),
      uiOutput("css_style"),
      h3("one"),
      h4("two"),
      h5("three")
    )
    
    server <- function(input, output, session) {
      
      style <- reactive({
        ifelse(
          test = input$selected_language == "lao",
          yes = "body { font-family: Phetsarath OT; }",
          no = "body { font-family: Arial, Helvetica, sans-serif; }"
        )
      })
      
      output$css_style <- renderUI({
        tags$head(
          tags$style(
            HTML(
              paste0(c(style(), css), collapse = "\n")
            )
          )
        )
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2020-06-23
    • 2018-04-30
    • 2013-09-27
    • 2021-04-18
    相关资源
    最近更新 更多