Shiny中DT::DataTables首列黑底白字且仅指定单个表格生效的实现方法
解决方法
1. 原理说明
你之前的方案作用于所有表格,是因为CSS选择器td.firstcol是全局匹配规则,所有携带firstcol类的单元格都会应用该样式。要仅作用于指定表格,只需要给CSS选择器加上对应表格的ID前缀(即你DTOutput里定义的outputId)即可,Shiny渲染DT表格时会将outputId作为表格外层容器的ID,通过ID限定即可实现样式隔离。
2. 修改后的完整代码
library(shiny) library(DT) # CSS选择器增加#tbl前缀,仅匹配ID为tbl的表格 CSS <- HTML( "#tbl td.firstcol {color: white; background-color: black}" ) ui <- fluidPage( tags$head( tags$style(CSS) ), fluidRow( column(3, DTOutput(outputId = 'tbl') ), column(3, DTOutput(outputId = 'tbl2') ) ) ) server <- function(input, output) { output$tbl<- renderDT({ datatable( data.frame( Label = c('Label1', 'Label2', 'Label3', 'Label4'), Data = c('Data1', 'Data2', 'Data3', 'Data4') ), rownames = FALSE, colnames = "", options = list( dom = 't', columnDefs = list( list(targets = 0, className = "firstcol") ) ) ) }) output$tbl2 <- renderDT({ datatable( data.frame( Label = c('Label1', 'Label2', 'Label3', 'Label4'), Data = c('Data1', 'Data2', 'Data3', 'Data4') ), rownames = FALSE, colnames = "", options = list( dom = 't' # 已移除tbl2的className配置,即使保留也不会应用样式 ) ) }) } # Run the application shinyApp(ui = ui, server = server)
3. 扩展说明
如果你后续需要给tbl2也单独设置其他首列样式,只需要新增一条前缀为#tbl2的CSS规则即可,比如:
#tbl2 td.firstcol {color: yellow; background-color: blue}
然后给tbl2的columnDefs加上对应的className配置即可实现两个表格的样式完全隔离。
内容的提问来源于stack exchange,提问作者KirkD-CO
相关产品推荐
相关产品推荐

