[英]r - How do I automatically scroll to the bottom of a div in shinyapp?
每當添加新內容時,我都希望將滾動條保持在底部。
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(“ myJSfile.js”),但沒有用。
我做錯了什么?
提前謝謝了。
這對我有用:
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。 讓我知道這個答案是否令人費解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.