如何在R Shiny中为单个选择菜单样式化样式?

12

你能否将CSS样式应用于单个selectInput菜单?

我在其他文章中找到了处理selectInput菜单样式的代码,但结果会影响应用程序中的所有菜单。我想只操作单个菜单。我还考虑根据服务器上发生的条件,在单个元素上添加样式,但那是另一个单独问题。

测试应用程序代码:

library(shiny)
library(shinydashboard)
library(shinyjs)
ui  <- 
  fluidPage(
  hr("how do we get the change the style elements of a single select input?) 
tags$style(type='text/css',  .selectize-input  { font-size: 8px; line-height: 8px;} 
             .selectize-dropdown { font-size: 8px; line-height: 8px; }"),

    selectInput("choice", "choices", c("A", "B", "C")),

    selectInput("choice2", "choices", c("D", "E", "F"))
     )

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

这种方法直接来自Dean Attali在这里的回答:examp,还有一个类似的问题被提出作为最后的评论,但没有得到答复,因此我决定就这个问题发布一个帖子,因为我也有同样的问题。

对于其他元素,比如textInput字段,我通常是这样做的:

tags$style(type='text/css', "#NAMEELEMENT {background-color: green; height: 40px; border-color: #bfbfbf; width: 520px; position: relative;left: 3%}"), 
您可以通过使用 # 和其输入ID 来将标记 $style 附加到元素上。
干杯。

1
也许这会有所帮助 https://dev59.com/zFoU5IYBdhLWcg3w9KTq#36908030。请注意,`.js-irs-0` 是滑块1,.js-irs-1 是滑块2,以此类推。 - Pork Chop
2
我实际上在我的滑块中使用了那个答案。它有效,但有一个很严重的缺点。如果我稍后在应用程序中添加另一个滑块,我想我必须重新计算所有 .js-irs-0 .irs-single, .js-irs-0 元素。即容易出现错误! - Mark
3个回答

10
我自己找到了答案。坚定的意念、大量在Google和Stackoverflow上花费的时间以及我发现的一些Dean Atali创建的信息组合起来,似乎可以解决这个问题:
  tags$head(tags$style(HTML('.selectize-input {white-space: nowrap}
    #choice+ div>.selectize-dropdown{width: 660px !important}
    #choices+ div>.selectize-dropdown{width: 300px !important}')))

1
这段时间没有白费,它对我帮助很大 :-) - agenis

8

将您的selectInput包装在div中:

tags$div(id='my_div',
         class='my_class',
         selectInput("choice",
                     "choices",
                      c("A", "B", "C"))),

然后你可以对它进行样式设置,而不会影响其他 selectInput 元素:

#my_div .selectize-dropdown-content > .option {
   background-color: grey;
}

或者

.my_class .selectize-dropdown-content > .option {
   background-color: grey;
}

与CSS一贯的做法一样,使用id来命名和捕获单个元素,使用class来为多个元素设置样式。


这似乎是做这件事情的“正确”方式,但如果我只想为一个输入添加样式,我通常的做法是将样式直接放入 div 中。做法如下:div(selectInput(...), style = "background-color: grey;")。如果只有一个要修改的输入,则看起来效果还不错。 - jamesguy0121

4

谢谢您,非常有用!

我用一个可行的实例包装了您的回答:

library(shiny)

ui <- fluidPage(
  tags$head(tags$style(HTML('
    .selectize-input {white-space: nowrap}
    #input1+ div>.selectize-dropdown{width: 660px !important; font-style: italic; font-weight: bold; color: green;}
    #input1+ div>.selectize-input{width: 660px !important; font-style: italic; font-weight: bold; color: green; margin-bottom: -10px;}
    #input2+ div>.selectize-dropdown{width: 300px !important; color: red;}
    #input2+ div>.selectize-input{width: 300px !important; color: red; margin-bottom: 0px;}
                            '))),

  selectizeInput("input1", "label1", c("A", "B", "C")),
  selectizeInput("input2", "label2", c("D", "E", "F"))
)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接