闪亮的自动向下滚动PRE元素

czfnxgou  于 2023-02-26  发布在  其他
关注(0)|答案(2)|浏览(111)

这是我的MWE:

library(shiny)

ui <- fluidPage(
  uiOutput("log"),
  actionButton("test","Click")
)

server <- function(input, output,session) {
  
  RV<-reactiveValues(myText=as.character())
  
  observeEvent(input$test,{
    text<-as.character()
    for (i in 1:100) text<-paste0(text,"hello ",i,"\n")
    RV$myText<-text
  })
  
  output$log<-renderUI({
    sHtml<-paste0("<pre id=\"preLog\" style=\"width:100px;height:200px;overflow:auto\">",RV$myText,"</pre>")
    print(HTML(sHtml))
  })

}

shinyApp(ui = ui, server = server)

当我点击按钮时,pre元素被填充,但它显示的行在顶部。我怎样才能使它自动滚动到底部?
谢谢!

mwecs4sa

mwecs4sa1#

这里有一个方法,我使用verbatimTextOutput,它生成一个pre元素。

library(shiny)

js <- "
$(document).on('shiny:value', function(evt){
  if(evt.name == 'log'){
    setTimeout(function(){
      var objDiv = document.getElementById('log');
      objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
    }, 0); 
  }
});
"

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js)),
    tags$style(HTML("#log {width:100px; height:200px; overflow:auto;}")), 
  ),
  br(),
  verbatimTextOutput("log"),
  actionButton("test", "Click")
)

server <- function(input, output, session) {
  
  RV <- reactiveValues(myText = as.character())
  
  observeEvent(input$test,{
    text <- as.character()
    for (i in 1:100) text <- paste0(text, "hello ", i, "\n")
    RV$myText <- text
  })
  
  output$log <- renderText({ RV$myText })
  
}

shinyApp(ui, server)
ws51t4hk

ws51t4hk2#

已修复:
遵循Stéphane溶液并将getElementById('log');变更为getElementById('preLog')

library(shiny)
library(shinyjs)

js <- "
$(document).on('shiny:value', function(evt){
  if(evt.name == 'log'){
    setTimeout(function(){
      var objDiv = document.getElementById('preLog');
      objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
    }, 0); 
  }
});
"

ui <- fluidPage(
  tags$head(
  tags$script(HTML(js))
  )
  ,uiOutput("log")
  ,actionButton("test","Click")
)

server <- function(input, output,session) {
  
  RV<-reactiveValues(myText=as.character())
  
  observeEvent(input$test,{
    text<-as.character()

    for (i in 1:100) text<-paste0(text,"hello ",i,"\n")
    RV$myText<-text

    
  })
  
  output$log<-renderUI({
  sHtml<-paste0("<pre id=\"preLog\" style=\"width:100px;height:200px;overflow:auto\">",RV$myText,"</pre>")
  print(HTML(sHtml))
  })

}

shinyApp(ui = ui, server = server)

相关问题