r - 如何在shinyapp中自动滚动到div的底部?

时间:2016-04-17 14:21:17

标签: javascript css r shiny

我想在添加新内容时将滚动条保留在底部。

printText <- function() {
  for(i in 1:20){
    Sys.sleep(0.1)
    shinyjs::html("text", paste("My text", i, "<br>"), add = TRUE)
    y = i + 1
  }
  return(y)
}
library(shiny)
library(shinyjs)
runApp(list(
  ui = shinyUI(fluidPage(
    shinyjs::useShinyjs(),
    titlePanel("Print consol output"),
    sidebarLayout(
      sidebarPanel(actionButton("go", "Go")),
      mainPanel(
        style = "overflow-y:scroll; max-height: 100px; position:relative;",
        div(id = "text")
      )
    )
  )),
  server = shinyServer(function(input, output, session){
    observeEvent(input$go, {
      shinyjs::html("text", "")
      y <- printText()
    })
  })
))

我找到了调用javascript的相关解决方案,但它在我的案例中并没有起作用。

这里是js代码:

function scrollToBottom(){
  var elem = document.getElementById('text');
  elem.scrollTop = elem.scrollHeight;
};

我尝试在div之前添加includeScript来调用该函数,例如includeScript(&#34; myJSfile.js&#34;),但它没有用。

我做错了什么?

非常感谢提前。

1 个答案:

答案 0 :(得分:2)

这对我有用:

library(shiny)

ui <- fluidPage(
  tags$head(
    # Some css to style the div to make it more easily visible
    tags$style(
      '#outDiv{
        height:150px;
        overflow-y:scroll;
        border: 1px solid black;
        border-radius:15px;
        padding:15px;
      }
      '
    ),
    # Custom shiny to javascript binding
    # scrolls "outDiv" to bottom once called
    tags$script(
      '
      Shiny.addCustomMessageHandler("scrollCallback",
        function(color) {
          var objDiv = document.getElementById("outDiv");
          objDiv.scrollTop = objDiv.scrollHeight;
        }
      );'
    )
  ),
  sidebarLayout(
    sidebarPanel(
      actionButton('go','Start Printing')
    ),
    mainPanel(
      div(id='outDiv',
        htmlOutput('out')
      )
      # Text output

    )
  )
)

server <- function(input, output, session) {
  autoInvalidate <- reactiveTimer(250, session) # Timer function

  ptm      <- proc.time() # Start time
  startTxt <- ''          # Start string to show on screen

  # Function to print new line when reactiveTimer invalidates
  startPrint <- function(){
    output$out <- renderText({ 
      ctm <- proc.time() - ptm
      autoInvalidate() # Start invalidating function every n miliseconds

      # Format string to print
      curr.font <- sample(colours(distinct=T), 1) 
      curr.txt  <- sprintf('<font color="%s"> %4.2f</font> seconds from start <br>', curr.font, ctm[[3]]) 
      startTxt  <<- paste(startTxt, curr.txt, collapse = '')

      # Call custom javascript to scroll window
      session$sendCustomMessage(type = "scrollCallback", 1)

      return(startTxt)
    })
  }

  observeEvent(input$go,{
    startPrint()
  })
}

runApp(shinyApp(ui,server))

这里的技巧是我每次更新文本输出时都会调用Javascript函数来滚动div。如果这个答案令人费解,请告诉我。