如何使用 css 以特定颜色显示 Rhandsontable 中的特定列 header?

How to display specific column header in Rhandsontable in a particular color using css?

我想使用 css 将特定列的 header 颜色更改为特定颜色。例如,有人可以建议如何将 header、'mpg'、'hp' 和 'gear' 的颜色更改为红色,以及如何更改 'disp' 的颜色, 'wt' 和 'carb' 为蓝色 table?

我的问题和本论坛发的问题差不多

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  rHandsontableOutput("table1"),
  tags$style(type="text/css", "#table1 th {font-weight:bold;}")
)

server=function(input, output, session) {

  output$table1 <- renderRHandsontable({
    rhandsontable(head(mtcars),rowHeaders=F)
  })
}

shinyApp(ui,server)

它需要一些 HTML 的知识。一种方法是将列名从纯文本转换为 HTML:

library(shiny)
library(rhandsontable)
library(purrr)
library(glue)
table_headers <- colnames(mtcars)
table_headers_html <- purrr::map_chr(table_headers, function(column){
    if(column %in% c('mpg', 'hp', 'gear')){
        color = "red"
    } else if (column %in% c('disp', 'wt', 'carb')) {
        color = "blue"
    } else {
        color = "black"
    }
    glue::glue("<span style='color:{color}'>{column}</span>")
})
> table_headers_html
 [1] "<span style='color:red'>mpg</span>"    "<span style='color:black'>cyl</span>"  "<span style='color:blue'>disp</span>" 
 [4] "<span style='color:red'>hp</span>"     "<span style='color:black'>drat</span>" "<span style='color:blue'>wt</span>"   
 [7] "<span style='color:black'>qsec</span>" "<span style='color:black'>vs</span>"   "<span style='color:black'>am</span>"  
[10] "<span style='color:red'>gear</span>"   "<span style='color:blue'>carb</span>"

在 HTML 中拥有 headers 列后,您可以在服务器代码中执行以下操作:

server=function(input, output, session) {

    output$table1 <- renderRHandsontable({
        rhandsontable(
            head(mtcars),
            rowHeaders=F,
            colHeaders = table_headers_html
        )
    })
}