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

如何在R Shiny DT数据表中为长文本添加展开/收起按钮?

在R Shiny的DT数据表中实现长文本展开/收起功能

下面是适配Shiny DT环境的完整解决方案,实现长文本单元格的"展开/收起"按钮功能:

library(shiny)
library(DT)
library(shinipsum)

text_df = data.frame(
  numbers = 1:3,
  letters = LETTERS[1:3],
  text = c("Lorem", substr(shinipsum::lorem, 1, 100), substr(shinipsum::lorem, 1, 5000))
)

ui <- fluidPage(
  tags$head(
    tags$style(HTML("
      .truncated-text {
        max-height: 80px;
        overflow: hidden;
        position: relative;
        padding-bottom: 20px;
      }
      .read-more-btn {
        position: absolute;
        bottom: 0;
        right: 0;
        background: white;
        border: none;
        color: #007bff;
        cursor: pointer;
        font-size: 14px;
      }
      .read-more-btn:hover {
        text-decoration: underline;
      }
    ")),
    tags$script(HTML("
      $(document).on('click', '.read-more-btn', function() {
        const textContainer = $(this).prev('.truncated-text');
        if (textContainer.css('max-height') === '80px') {
          textContainer.css('max-height', 'none');
          $(this).text('收起');
        } else {
          textContainer.css('max-height', '80px');
          $(this).text('展开');
        }
      });
    "))
  ),
  dataTableOutput("text_table")
)

server <- function(input, output) {
  output$text_table = renderDataTable({
    datatable(text_df, escape = FALSE, options = list(
      columnDefs = list(list(
        targets = 3, # 针对第4列(text列,索引从0开始)
        render = JS("function(data, type, row) {
          if(type === 'display') {
            return '<div class=\"truncated-text\">' + data + '</div><button class=\"read-more-btn\">展开</button>';
          }
          return data;
        }")
      ))
    ))
  })
}

shinyApp(ui = ui, server = server)

关键实现说明:

  1. CSS样式定义:
    • 给长文本容器设置max-height和overflow: hidden,实现文本截断效果
    • 给按钮设置绝对定位,固定在单元格右下角
  2. JavaScript交互逻辑:
    • 监听按钮点击事件,切换文本容器的max-height属性,实现展开/收起
    • 同步切换按钮显示文本为"展开"或"收起"
  3. DT数据表配置:
    • 开启escape = FALSE,允许渲染HTML内容
    • 通过columnDefs的render函数,给目标列的文本包裹容器和按钮
    • 仅在display模式下处理渲染,不影响数据表的导出等功能

注意事项:

  • 代码中targets = 3对应数据表的第4列(索引从0开始),可根据实际列位置调整
  • 可修改CSS中的max-height值,调整默认显示的文本行数
  • 按钮样式可根据需求自定义颜色、字体等属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:40:24