【问题标题】:R Shiny DataTable selected row colorR Shiny DataTable 选定的行颜色
【发布时间】:2017-12-11 13:57:47
【问题描述】:

我正在尝试在我闪亮的应用程序中为 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 包有一些内置函数来改变字体颜色/背景颜色。见here
  • @GregordeCillia 我看过那些,但我不知道如何根据是否选择为一行着色。
  • 您可以使用dataTableProxy 并在input$table_rows_selected 更改时更新样式
  • 等等...代理没有 formatStyle 等价物。也许这种方法行不通。
  • @GregordeCillia 是的,我正要说我无法让它工作......还有其他想法吗? :)

标签: javascript css r datatables shiny


【解决方案1】:

这应该可以完成工作:

#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))

【讨论】:

  • 非常感谢以上内容,它帮助我解决了类似的问题。要为选定的行和列设置不同的颜色,请使用:tags$style(HTML('table.dataTable tr.selected td{background-color: pink !important;}')), tags$style(HTML('table.dataTable td.selected {background-color: orange !important;}'))
猜你喜欢
  • 1970-01-01
  • 2019-07-07
  • 2015-11-13
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 2019-09-12
  • 1970-01-01
相关资源
最近更新 更多