如何在R Shiny中修改DT Datatable表头的背景色和文字颜色
解决方案
formatStyle()仅作用于表格数据单元格,要修改表头样式有两种常用实现方式:
方法1:添加自定义CSS(推荐,兼容性好)
直接在Shiny UI中插入针对DT表头的CSS规则,全局生效,修改简单:
library(shiny) library(dplyr) library(DT) ui <- fluidPage( # 加入自定义CSS tags$style(HTML(" table.dataTable thead th { background-color: red !important; color: white !important; } ")), sidebarLayout( sidebarPanel( ), mainPanel( DTOutput("table") ) )) server <- function(input, output) { data <- tibble(name = c("Justin", "Corey", "Sibley"), grade = c(50, 100, 100)) output$table <- renderDT({ datatable(data) }) } shinyApp(ui = ui, server = server)
如果需要仅针对特定表格生效,给表格加ID选择器即可,比如上述示例的表格ID是table,CSS规则可改成#table table.dataTable thead th。
方法2:通过datatable的initComplete参数配置
如果不想修改全局CSS,可以在渲染表格时通过JS动态修改样式,仅对当前表格生效:
output$table <- renderDT({ datatable(data, options = list( initComplete = JS( "function(settings, json) {", "$(this.api().table().header()).css({'background-color': 'red', 'color': 'white'});", "}") ) ) })
使用该方法需要提前加载DT包,JS函数是DT内置支持的配置项。
内容的提问来源于stack exchange,提问作者J.Sabree
相关产品推荐
相关产品推荐

