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

如何为Shiny容器添加滚动标签并实现内容新增时自动滚到底部?

实现Shiny容器内容添加时自动滚动到底部

你可以通过JavaScript操作DOM元素的滚动属性,结合shinyjs执行脚本,实现内容添加后自动滚动到底部的效果。具体修改如下:

在每次调用shinyjs::html添加内容后,执行一段JS代码,将目标容器的scrollTop设置为其scrollHeight(即容器内容的总高度),这样就能自动滚动到最新内容的位置。

修改后的完整代码:

library(magrittr)
pkgs <- c(
  "lorem",
  "shiny",
  "shinyjs",
  "stringi"
)
for (pkg in pkgs) requireNamespace(pkg)

ui <- shiny::fluidPage(
  shinyjs::useShinyjs(),
  shiny::sidebarPanel(
    shiny::actionButton(
      inputId = "loreming",
      label   = "Add more"
    )
  ),
  shiny::mainPanel(
    shiny::verbatimTextOutput("muchlorem", placeholder = TRUE),
    shiny::tags$head(
      shiny::tags$style(
        "#muchlorem{overflow-y: scroll; max-height: 200px;}"
      )
    )
  )
)

server <- function(input, output, session)
{
  shiny::observeEvent(input$loreming, {
    shinyjs::html(
      id = "muchlorem",
      html = lorem::ipsum(5) %>%
        stringi::stri_wrap(prefix = "\n") %>%
        paste(collapse = ""),
      add = TRUE)
    
    # 新增:执行JS实现自动滚动到底部
    shinyjs::runjs("
      const container = document.getElementById('muchlorem');
      container.scrollTop = container.scrollHeight;
    ")
  })
}

shiny::shinyApp(ui, server)

这段新增的JS代码会找到muchlorem容器,直接将滚动位置设置为容器内容的总高度,确保每次添加新内容后,容器自动滚动到最底部。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:07:17