R 数据 Table 交替行颜色与分组

R Data Table Alternating Row Color with Groupings

我有一个闪亮的仪表板,里面有一个数据 table,我想自定义交替行的颜色。我能够找到 CSS 来指定奇数行和偶数行颜色,但是因为我使用的是 RowGroup 扩展,所以它没有按预期工作。它正在将组 header 计为一行。

“男性”组的第一行应该是白色,而不是蓝色。希望这是一个快速 CSS 修复。提前致谢!

下面是一个简短的可重现示例:

### Short reproducable example for alternating rows in datatable
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:odd').css('background-color', 'white');",
                     "$('table.dataTable.display tbody tr:even').css('background-color', '#e4f0f5');",
                     "}")
                   
                   
    ),
    escape = FALSE)
  
}

shinyApp(ui = ui, server = server)

它已经分配了 类 奇数和偶数,您只需再次使用 tr:odd 和 tr:even 在整个 table 上“重做”,这会导致问题。

修复很简单,将你的JS代码中的tr:odd和tr:even替换为tr.odd和tr.even