如何在闪亮中以编程方式转到 HTML 锚点?



我可以使用a("Go to Results", href = '#anchor_box')在 ui 中添加指向锚点的链接,并让用户单击它以转到此锚点。

但是如何以编程方式将窗口"发送到"#anchor_box?例如,当运行时间较长的observeEvent()结束时有结果时?

你可以使用javascript来实现这一点。有几种可能性,一种方法是获取元素并使用scrollIntoView(),请参阅使用 javascript 的锚点跳转。

shiny中使用javascript的一个简单方法是library(shinyjs)

可以插入以下内容以指示 R 在焦点中移动元素:

runjs('
document.getElementById("anchor_box").scrollIntoView();
')

为了知道何时这样做,您可以将其包装在observeEvent()中:

observeEvent(eventExpr = input$clck, handlerExpr = {...})

缺点是刷新页面不会自动"向上滚动到顶部"。

可重现的示例:

library(shiny)
library(shinyjs)
ui <- fluidPage(
a("Go to Results", href = '#anchor_box'),
actionButton("clck", "Move Programmatically!"),
plotOutput("plot", height = 1300),  
div(id = "anchor_box", "HERE"),
useShinyjs(),
)
server <- function(input, output, session) {
output$plot <- renderPlot({
plot(1)
})
observeEvent(eventExpr = input$clck, handlerExpr = {
runjs('
document.getElementById("anchor_box").scrollIntoView();
')
})
}
shinyApp(ui, server)

最新更新