更改DATATABLE的背景颜色。

huangapple go评论67阅读模式
英文:

Change BG color of DATATABLE

问题

我想要更改此Datatable的第一行和最后一行的背景单元格颜色。如何在format_style()函数中指定这个?

df <- data.frame(categoria = c("A","B","C","D"),
                 posição = c(4,3,2,1))

DT::datatable(df) 
英文:

I want to change the color of background cell of the first and last row of this Datatable.
How can i specify this in format_style() function?

df &lt;- data.frame(categoria = c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;),
                 posi&#231;&#227;o = c(4,3,2,1))


DT::datatable(df)

答案1

得分: 1

你可以使用类似以下的方法 - DataTables API、jQuery 和 JavaScript 的混合:

library(DT)

df = data.frame(
  category = c("A","B","C","D"),
  position = c(4,3,2,1)
)

datatable(df, options = list(
  initComplete = JS(
    "function(settings, json) {",
    "  var allNodes = this.api().table().rows().nodes().toArray();",
    "  var firstLast = [ allNodes[0], allNodes[allNodes.length -1] ];",
    "  $(firstLast).css({'background-color': 'red', 'color': 'white'});",
    "}"
  )
))

这将产生以下结果:

更改DATATABLE的背景颜色。


但这取决于你对“first”和“last”的具体含义。使用这种方法(使用 initComplete),当用户对行进行排序/筛选时,格式将随着行数据移动。因此,最初的“first”和“last”可能会改变。


参考资料:

英文:

You can use something like this - a mix of the DataTables API, jQuery and JavaScript:

library(DT)

df = data.frame(
  category = c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;),
  position = c(4,3,2,1)
)


datatable(df, options = list(
  initComplete = JS(
    &quot;function(settings, json) {&quot;,
    &quot;  var allNodes = this.api().table().rows().nodes().toArray();&quot;,
    &quot;  var firstLast = [ allNodes[0], allNodes[allNodes.length -1] ];&quot;,
    &quot;  $(firstLast).css({&#39;background-color&#39;: &#39;red&#39;, &#39;color&#39;: &#39;white&#39;});&quot;,
    &quot;}&quot;)
))

Which results in the following:

更改DATATABLE的背景颜色。


But this depends on what exactly you mean by "first" and "last". With this approach (using initComplete), the formatting will move with the row data, when the rows are sorted/filtered by the user. So, what starts out as "first" and "last" may change.


References:

huangapple
  • 本文由 发表于 2023年4月6日 22:35:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定