R Shiny DataTable 选定行的颜色

8

我想在我的Shiny应用程序中为选定的DataTable行设置高亮颜色。基本上,我希望选定行的颜色是红色而不是蓝色。然而,我对JavaScript一点也不熟悉,所以我很难编写适当的回调函数(至少我认为这是问题所在)。到目前为止,我尝试过以下方法:

# ui.R
library(shiny)

fluidPage(
  title = 'DataTables Test',
  DT::dataTableOutput('table')
)

# server.R
library(shiny)
library(DT)

# render the table
output$table = renderDataTable(datatable(head(iris, 20), 
options = list(
    initComplete = JS(
      "function(settings, json) {",
      "var rows = $(this.api().table().rows());",
      "for (var i = 0; i < rows.length; i++){ ",
      "var row = rows[i];",
      "row.css({'background-color': '#000', 'color': '#f00'})",
      "}",
      "}")
  )))

})

正如您所看到的,目前我只是在尝试弄清如何更改行颜色。一旦我弄清楚了这一点,我将尝试将CSS更改为:

"tr.selected td, table.dataTable td.selected { background-color: #f00}"

但我还没有达到那个目标 - 不幸的是,上面的代码对背景颜色没有任何作用。如果有人能帮我找到完整的解决方案,那就太好了。


DT 包含一些内置函数,可用于更改字体颜色/背景颜色。请参见此处 - Gregor de Cillia
@GregordeCillia 我看过了那些,但我无法弄清楚如何根据是否选择来着色一行。 - James Allingham
您可以使用 dataTableProxy,并在 input$table_rows_selected 更改时更新样式。 - Gregor de Cillia
等一下...对于代理,没有formatStyle的等效物。也许这种方法行不通。 - Gregor de Cillia
@GregordeCillia 是的,我正要说我无法让它工作...还有其他想法吗? :) - James Allingham
2个回答

19

这应该可以完成任务:

#rm(list = ls())
library(shiny)
library(DT)

ui <- basicPage(
  tags$style(HTML('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))

输入图像描述


2
非常感谢以上信息,它帮助我解决了一个类似的问题。要为选定的行和列设置不同的颜色,请使用以下代码:tags$style(HTML('table.dataTable tr.selected td{background-color: pink !important;}')), tags$style(HTML('table.dataTable td.selected {background-color: orange !important;}')) - Hester Lyons

2
如果有人遇到和我一样的问题:如果你在datatable中使用了“bootstrap”样式,你需要将“.selected”改为“.active”,否则它不会起作用。例如,在Pork Chop提供的答案中。
library(shiny)
library(DT)

ui <- basicPage(
  tags$style(HTML('table.dataTable tr.active td, table.dataTable tr.active {background-color: pink !important;}')),
  mainPanel(DT::dataTableOutput('mytable'))
)    

server <- function(input, output,session) {
  output$mytable = DT::renderDataTable(    
    datatable(mtcars, style="bootstrap")
  ) 
}

runApp(list(ui = ui, server = server))

自从DataTables v1.12版本以后,background-color不再起作用:现在控制行颜色的属性是box-shadow(参见:https://datatables.net/blog/2022-05-13#Row-colouring-improvementshttps://www.w3schools.com/CSSREF/css3_pr_box-shadow.php)。
tags$style(HTML('table.dataTable tr.selected td, table.dataTable tr.selected {box-shadow: inset 0 0 0 9999px pink !important;}'))

使用“bootstrap”样式:
tags$style(HTML('table.dataTable tr.active td, table.dataTable tr.active {box-shadow: inset 0 0 0 9999px pink !important;}'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接