如何在Shiny中同步两个rhandsontable的垂直滚动?
实现Shiny中两个rhandsontable的垂直滚动同步
要实现两个rhandsontable的垂直滚动同步,需要借助JavaScript监听滚动事件并同步滚动位置。以下是可直接运行的完整代码:
library(shiny) library(shinydashboard) library(rhandsontable) ui = dashboardPage( skin="red", dashboardHeader(title="App"), dashboardSidebar(), dashboardBody( # 自定义JS实现滚动同步 tags$script(HTML(" $(document).on('shiny:value', function(event) { // 等待两个表格完成渲染 if (event.target.id === 'A' || event.target.id === 'B') { const tableA = $('#A').find('.ht_master')[0]; const tableB = $('#B').find('.ht_master')[0]; if (tableA && tableB) { // 同步A到B的垂直滚动 tableA.addEventListener('scroll', function() { tableB.scrollTop = tableA.scrollTop; }); // 同步B到A的垂直滚动 tableB.addEventListener('scroll', function() { tableA.scrollTop = tableB.scrollTop; }); } } }); ")), div(style="white-space:nowrap;overflow-x:auto;overflow-y:hidden", div(style="display:inline-block", rHandsontableOutput("A") ), div(style="display:inline-block;margin-left:35px", rHandsontableOutput("B") ) ) ) ) server = shinyServer(function(input, output, session){ A = as.data.frame(matrix(rnorm(1600),40,40)) B = as.data.frame(matrix(rnorm(1600),40,40)) output$A <- renderRHandsontable({ rhandsontable(A, height = 500, width = 1000) }) output$B <- renderRHandsontable({ rhandsontable(B, height = 500, width = 1000) }) }) runApp(list(ui=ui, server=server))
关键说明
- rhandsontable基于Handsontable JS库,其滚动容器的类名为
.ht_master,我们需要获取这个容器元素来监听滚动事件。 - 使用
shiny:value事件确保在表格渲染完成后再绑定滚动监听,避免因DOM元素未加载导致的错误。 - 双向绑定滚动事件:滚动任意一个表格时,另一个表格的
scrollTop(垂直滚动位置)会同步更新,实现滚动同步。
内容的提问来源于stack exchange,提问作者Jordi Legorreta
相关产品推荐
相关产品推荐

