You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义Shiny中含复选框的DT表格列宽度?

解决Shiny模块中DT复选框列过宽的问题

在Shiny模块里使用DT表格时,复选框列过宽的问题,核心原因是你在columnDefs里重复设置className导致样式覆盖,同时需要微调CSS消除多余内边距。以下是修复后的完整代码:

关键修改点

  • 合并columnDefs中的类名:将dt-center和low_checbox_width放在同一个className值里,用空格分隔,避免样式覆盖
  • 强化CSS样式:重置shiny-input-container的内外边距,给复选框列的单元格加上强制内边距,彻底消除多余空间
  • 修正行索引:DT表格行从0开始计数,回调函数里的行号需要减1才能正确对应
  • 启用autoWidth:让DT自动适配其他列宽度,避免复选框列缩窄后其他列布局异常
library(DT)
library(shiny)

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
  }
  inputs
}

module_ui <- function(id){
  ns <- NS(id)
  
  fluidRow(
    tags$head(tags$style(
      'td.low_checbox_width .shiny-input-container{
        width:auto;
        margin:0;
        padding:0;
      } 
      td.low_checbox_width{
        width:30px;
        padding:4px !important;
      }'
    )),
    DTOutput(ns("mytable"))
  )
}

module_server <- function(input, output, session){
  ns <- session$ns
  
  output$mytable = renderDT({
    datatable(
      cbind(flag = shinyInput(checkboxInput, nrow(iris), "checkb"), iris),
      rownames = FALSE,
      colnames =  c("", colnames(iris)),
      escape = FALSE,
      options = list(
        autoWidth = TRUE,
        columnDefs = list(
          list(
            className = "dt-center low_checbox_width",
            targets = 0
          )
        )
      ),
      callback = JS(
        "table.on('change', '[id^=checkb]', function(){",
        "  var id = this.getAttribute('id');",
        "  var i = parseInt(/checkb(\\d+)/.exec(id)[1]);",
        "  var value = $(this).prop('checked');",
        "  var info = [{row: i-1, col: 0, value: value}];",
        sprintf(
          "Shiny.setInputValue('%s', info);", 
          ns(sprintf("%s_cell_edit:DT.cellInfo", "mytable"))
        ),
        "})"
      )
    )
  })
}

ui <- navbarPage(
  module_ui("module_id")
)
server <- function(input, output, session){
  callModule(module_server, "module_id")
}

shinyApp(ui, server)

内容的提问来源于stack exchange,提问作者tomsu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:55:35