R Shiny中带RowGroup扩展的DT表格交替行颜色自定义问题
问题原因
你使用的全局奇偶行选择器会将RowGroup扩展自动生成的分组表头行(默认携带dt-row-group类)计入行计数,导致数据行的交替色顺序被打乱。
修复方案
只需修改renderDT中initComplete的JS代码,先筛选排除分组表头行,再对普通数据行设置交替色即可,你也可以根据需求自定义分组行的背景色。
修改后的initComplete代码如下:
initComplete = JS( "function(settings, json) {", "$(this.api().table().header()).css({'background-color': '#00416B', 'color': 'white'});", // 自定义分组表头行背景色,可按需修改 "$('table.dataTable.display tbody tr.dt-row-group').css('background-color', '#f8f9fa');", // 筛选所有非分组的普通数据行 "const dataRows = $('table.dataTable.display tbody tr:not(.dt-row-group)');", // 按奇偶设置交替色,符合你原来的配色需求:首行白色,次行浅蓝色 "dataRows.filter(':even').css('background-color', 'white');", "dataRows.filter(':odd').css('background-color', '#e4f0f5');", "}" )
完整可运行代码
library(shiny) library(shinydashboard) library(shinycssloaders) library(dplyr) library(DT) data <- data.frame( Sex = c("Female", "Female", "Male", "Male", "Male"), First.Name = c("Mary", "Amy", "Connor", "Blaine", "Emily"), Last.Name = c("Frazier", "Jones", "Jones", "Black", "Rains") ) ui <- dashboardPage( dashboardHeader(title = "Dashboard", titleWidth =300 ), dashboardSidebar(width = 300, sidebarMenu(id = "sidebar", menuItem("User Guide", tabName = "userguide", icon = icon("question-circle")), menuItem("Dashboard", tabName = "dashboard", icon = icon("table"), selected = TRUE) ) ), dashboardBody( tabItems( tabItem(tabName = "userguide", fluidRow( box(width = 12 ) ) ), tabItem(tabName = "dashboard", fluidRow( box(width = 12, DTOutput("table") %>% withSpinner(color = "#00416B") ) ) ) ) ) ) server <- function(input, output) { output$table <- renderDT( data, rownames = FALSE, caption = htmltools::tags$caption( style = 'text-align: center; font-weight: bold; color:black', paste0("This list was generated on ", Sys.Date(), ".") ), extensions = c('Buttons', 'RowGroup', 'FixedHeader'), options = list(paging = FALSE, dom = 'Blft', fixedHeader = TRUE, buttons = list( list(extend = 'pdf', filename = paste0("List ", Sys.Date()), orientation = 'landscape') ), rowGroup = list(dataSrc = 0), initComplete = JS( "function(settings, json) {", "$(this.api().table().header()).css({'background-color': '#00416B', 'color': 'white'});", "$('table.dataTable.display tbody tr.dt-row-group').css('background-color', '#f8f9fa');", "const dataRows = $('table.dataTable.display tbody tr:not(.dt-row-group)');", "dataRows.filter(':even').css('background-color', 'white');", "dataRows.filter(':odd').css('background-color', '#e4f0f5');", "}" ) ), escape = FALSE) } shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者Melissa Salazar
相关产品推荐
相关产品推荐

