控制数据表输出中的行条纹颜色

Control row stripe color in datatable output

什么是"best"方法是在数据table(DT)中设置自定义行stripe/row条带颜色?

我正在使用数据table (DT) 创建交互式 tables(例如 HTML 通过 rmarkdown),具有下载能力等。这就是为什么我不是使用 Huxtable 或任何其他 table 格式包,理想情况下我不必在将 table 发送到 datatable 之前先在另一个包中设置样式 - 尽管打开如果 necessary/best 可用选项。

这是一个独立的行条纹示例,根据此处显示的示例修改,答案#1(https://src-bin.com/en/q/1b3261f), similar to this unsuccessful attempt。一个问题是悬停颜色不再有效,尽管它本来是应用到任何东西的色调?另一个是行颜色在按列重新排序后与原始行数据保持一致 - 不确定这种默认行为是否是我想要的 - 是否容易更改?

  DT::datatable(head(iris, 20),
                extensions = 'Buttons',
                options=list(dom = 'Bfrtip',
                             buttons = c('excel','csv','print'),
                             rowCallback=JS(
                               'function(row,data) {
     if($(row)["0"]["_DT_RowIndex"] % 2 <1) 
            $(row).css("background","#f2f9ec")
   }'))) 

这里有一个选项可以按值给单元格背景着色,这不是我想要的: color-cells-in-dt-datatable-in-shiny

Datatables(dot)net datatables.net/manual/styling/theme-creator 有一个示例样式表,它创建了一大堆 CSS(357 行代码),大概可以用于style.css 文件需要做什么(行条纹,自定义颜色)?当我认为达到我的目的的秘诀就是这行代码(如下)时,这对我来说似乎有点过分了。请注意,datatable 示例的默认行为具有独立于初始行号的条带化(上面的 c.f 代码,其中条带化与原始原始数据保持一致)。我可以将下面的代码直接放入 r datatable 代码中吗,例如像上面的例子吗?

table.dataTable.stripe tbody tr.odd, table.dataTable.display tbody tr.odd {`
background-color` `: ` `#f9f9f9` `; }`

你可以这样做:

library(DT)

callback <- c(
  "$('table.dataTable.display tbody tr:odd').css('background-color', 'green');",
  "$('table.dataTable.display tbody tr:even').css('background-color', 'red');",
  "$('table.dataTable.display tbody tr:odd')",
  "  .hover(function(){",
  "    $(this).css('background-color', 'yellow');",
  "   }, function(){",
  "    $(this).css('background-color', 'green');",
  "   }",
  "  );",
  "$('table.dataTable.display tbody tr:even')",
  "  .hover(function(){",
  "    $(this).css('background-color', 'orange');",
  "   }, function(){",
  "    $(this).css('background-color', 'red');",
  "   }",
  "  );"
)

datatable(iris, callback = JS(callback))


编辑

这是@Mark Neal 评论后的修复:

library(DT)

rowCallback <- c(
  "function(row, data, num, index){",
  "  var $row = $(row);",
  "  if($row.hasClass('even')){",
  "    $row.css('background-color', 'green');",
  "    $row.hover(function(){",
  "      $(this).css('background-color', 'yellow');",
  "     }, function(){",
  "      $(this).css('background-color', 'green');",
  "     }",
  "    );",  
  "  }else{",
  "    $row.css('background-color', 'cyan');",
  "    $row.hover(function(){",
  "      $(this).css('background-color', 'orange');",
  "     }, function(){",
  "      $(this).css('background-color', 'cyan');",
  "     }",
  "    );",  
  "  }",
  "}"  
)

datatable(iris, options = list(rowCallback = JS(rowCallback)))