R闪亮的应用程序,使日志自动向下滚动

问题描述 投票:1回答:1

我试图使登录闪亮,该文本取自函数更新的反应值。日志在verbatimTextOutput中,我想让它在每次更新时向下滚动。为此我使用javascript代码找到here的函数,但它在控制台更新后立即使用它不起作用,它实际上滚动到上一次更新的级别(因为UI值尚未更新? )。我尝试了不同的方法来在不同的时间启动该功能,并且无法将滚动条置于底部。

这是我正在尝试的示例,我希望“添加文本”按钮一直向下滚动,但只有“强制滚动更新”按钮才能执行此操作:

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = "shinyjs.scrollDown = function() {
                            var objDiv = document.getElementById('log');
                            objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
                          }"),
  tags$style(HTML("#log {height:80px}")), br(),
  verbatimTextOutput("log", placeholder = TRUE),
  actionButton("add", "Add Text"),
  actionButton("force", "Force scroll update")
)

server <- function(input, output, session) {

  a <- reactiveValues(
    logOutput = "TEST"
  )

  output$log <- renderText({ a$logOutput })

  updateLog <- function(text){
    a$logOutput <- paste(a$logOutput, text, sep = "\n")
  }

  observeEvent(input$add, {
    updateLog("TEST")
    js$scrollDown()
  })  

  observeEvent(input$force,{
    js$scrollDown()
  })

}

shinyApp(ui = ui, server = server)

我希望这可以做到,谢谢

javascript r shiny shinyjs
1个回答
2
投票

一个选项:

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

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),
  tags$style(HTML("#log {height:80px}")), br(),
  verbatimTextOutput("log", placeholder = TRUE),
  actionButton("add", "Add Text")
)

server <- function(input, output, session) {

  a <- reactiveValues(
    logOutput = "TEST"
  )

  output$log <- renderText({ a$logOutput })

  updateLog <- function(text){
    a$logOutput <- paste(a$logOutput, text, sep = "\n")
  }

  observeEvent(input$add, {
    updateLog("TEST")
  })  

}

使用MutationObserver解决方案没有延迟:

js <- "
$(document).ready(function(){
  var objDiv = document.getElementById('log');
  // create an observer instance
  var observer = new MutationObserver(function(mutations) {
    objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
  });
  // configuration of the observer
  var config = {childList: true};
  // observe objDiv
  observer.observe(objDiv, config);
})
"
© www.soinside.com 2019 - 2024. All rights reserved.