英文:
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 <- data.frame(categoria = c("A","B","C","D"),
posiçã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'});",
"}"
)
))
这将产生以下结果:
但这取决于你对“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("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'});",
"}")
))
Which results in the following:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论