You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在使用bslib主题的Shiny应用中修改数据表格选中行颜色

解决bslib主题下Shiny DT表格选中行颜色失效的问题

启用bslib主题后,自定义CSS会被主题样式覆盖,导致选中行颜色变回蓝色。可以通过以下几种方法解决:

方法1:提升CSS选择器特异性

给自定义选择器加上表格容器的ID,让样式优先级超过bslib主题的样式:

library(shiny)
library(DT)
library(bslib)

ui <- fluidPage(
  theme = bs_theme(),
  tags$style(HTML('
    #mytable table.dataTable tr.selected td, 
    #mytable table.dataTable td.selected {
      background-color: pink !important;
    }
  ')),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {
  output$mytable = DT::renderDataTable(    
    datatable(mtcars)
  ) 
}
runApp(list(ui = ui, server = server))

这里通过#mytable(表格输出的ID)限定选择范围,配合!important确保样式生效。

方法2:将样式嵌入bslib主题

直接把自定义CSS传入bs_theme()的additional_css参数,让样式作为主题的一部分加载:

library(shiny)
library(DT)
library(bslib)

ui <- fluidPage(
  theme = bs_theme(
    additional_css = '
      table.dataTable tr.selected td, 
      table.dataTable td.selected {
        background-color: pink !important;
      }
    '
  ),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {
  output$mytable = DT::renderDataTable(    
    datatable(mtcars)
  ) 
}
runApp(list(ui = ui, server = server))

这种方式无需额外的tags$style,样式优先级更高,不会被主题覆盖。

方法3:用DT的JS回调手动控制样式

通过DT的initComplete回调,用JavaScript手动处理选中行的样式:

library(shiny)
library(DT)
library(bslib)

ui <- fluidPage(
  theme = bs_theme(),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {
  output$mytable = DT::renderDataTable(    
    datatable(
      mtcars,
      options = list(
        initComplete = JS(
          "function(settings, json) {
            $(this.api().table().body()).on('click', 'tr', function() {
              $(this).toggleClass('selected');
              $(this).find('td').css('background-color', $(this).hasClass('selected') ? 'pink' : '');
            });
          }"
        )
      )
    )
  ) 
}
runApp(list(ui = ui, server = server))

这种方法绕开CSS优先级问题,直接通过JS动态设置样式。

内容的提问来源于stack exchange,提问作者ashcrashbegash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:53:28