R Shiny如何修改DT表格上下方文字颜色适配黑色背景
R Shiny 深色主题下DT表格样式适配方案
实现要求
无需接入JavaScript,仅通过CSS完成以下适配,适配cyborg黑色系主题:
- 表格上方
Show entries条目数选择标签、Search:搜索标签、底部分页信息、页码按钮文字设置为白色,保证黑底下可读性 - 保留表格主体默认白色背景,表格行内容文字保持默认黑色
- 搜索输入框、条目数选择下拉框保持白色背景,框内输入/选中的文字保持黑色
原有样式问题
原有自定义CSS选择器覆盖范围过大,未区分DT表格外围控件区和表格内容区,导致出现非列表头文字变灰、表格背景被误改为黑色的异常效果。
修正后代码
将原有UI部分的tags$style内容替换为精准匹配的CSS规则即可,完整可运行代码如下:
library(shiny) library(shinythemes) library(DT) ui = navbarPage( tags$style(" /* DT外围控件文字设为白色 */ .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_paginate { color: #ffffff !important; } /* 搜索框、条目下拉框保持白底黑字 */ .dataTables_wrapper .dataTables_filter input, .dataTables_wrapper .dataTables_length select { color: #000000 !important; background-color: #ffffff !important; border: 1px solid #cccccc; } /* 表头文字白色 */ .dataTable thead th { color: #ffffff !important; } /* 表格主体强制白底黑字,避免被主题覆盖 */ .dataTable tbody td { color: #000000 !important; background-color: #ffffff !important; } /* 分页按钮文字适配 */ .dataTables_wrapper .dataTables_paginate .paginate_button { color: #ffffff !important; } .dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button:hover { color: #000000 !important; } "), title = div("Projects"), theme = shinytheme("cyborg"), tabPanel("GIS Projects", icon = icon("info"), div(p(h1("Instructions:"),style="text-align: justify;")), p("1. The user can upload a CSV file.", style="color:white"), p("2. Based on the uploaded file, the app will return an interactive table that is searchable.", style="color:white"), p("3. Based on the uploaded file, the app will allow the user to add their project details in new rows or delete existing ones.", style="color:white"), uiOutput("all"), sidebarLayout( sidebarPanel( radioButtons( "File_Type", label = "Choose File type", choices = list(".csv/txt" = 1, ".xlsx" = 2), selected = 1, inline = TRUE ), fileInput('file2', 'Upload Your Data', accept = c( 'text/csv', 'text/comma-separated-values,text/plain', '.csv', '.xlsx' ))), mainPanel( downloadButton("download1","Download data as csv"), DTOutput("contents")),) ) ) # 服务端逻辑 server <- function(input, output) { myData = reactive({ req(input$file2) inFile = input$file2 if (is.null(inFile)) return(NULL) data = read.csv(inFile$datapath, header = TRUE) data }) output$contents = renderDT({ req(myData()) myData() }) } # 启动应用 shinyApp(ui = ui, server = server)
样式说明
- 所有CSS规则均通过
.dataTables_wrapper作用域限定,仅修改DT生成的表格相关元素,不会影响页面其他组件 - 加
!important是为了覆盖cyborg主题自带的样式优先级,避免样式不生效 - 没有修改表格行的hover、选中样式,如果需要调整可以在上述CSS基础上追加对应规则即可
内容的提问来源于stack exchange,提问作者Ed_Gravy
相关产品推荐
相关产品推荐

