R语言 访问UI元素的当前位置

mfpqipee  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(94)

我想知道是否可以访问UI元素的当前位置(或者宽度和高度)(在本例中由uiOutput生成),这样我就可以知道它占用了多少空间,并且可以相应地调整其他元素的大小。

library(shiny)

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
          "There is some more stuff here normally"
        ),

        # Show a plot of the generated distribution
        mainPanel(
          uiOutput("ui_element"),
          plotOutput("plot")
        )
    )
)

server <- function(input, output) {
    output$ui_element <- renderUI({
      "This is just some text to demonstrate. Usually there are some pictures embedded here as well,
      this is why it I use renderUI. I would like to know the position / size of this ui element"
      })
    output$plot <- renderPlot({
        plot(1:5,1:5)
    })
}
# Run the application 
shinyApp(ui = ui, server = server)

字符串
我还没有找到任何关于这个主题,但也许我正在寻找错误的东西,所以任何帮助将不胜感激

72qzrwbm

72qzrwbm1#

只需对answer here做一个小的修改,就可以得到div的大小而不是窗口的大小。

library(shiny)

ui <- fluidPage(
  tags$head(tags$script('
      var dimension = [0, 0];
      $(document).on("shiny:connected", function(e) {
          const ele = document.getElementById("ui_element")
          dimension[0] = ele.getBoundingClientRect().width;
          dimension[1] = ele.getBoundingClientRect().height;
          Shiny.onInputChange("dimension", dimension);
      });
      $(window).resize(function(e) {
          const ele = document.getElementById("ui_element")
          dimension[0] = ele.getBoundingClientRect().width;
          dimension[1] = ele.getBoundingClientRect().height;
          Shiny.onInputChange("dimension", dimension);
      });
  ')),
  sidebarLayout(
    sidebarPanel(
      "There is some more stuff here normally"
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      uiOutput("ui_element"),
      plotOutput("plot"),
      uiOutput("div_size")
    )
  )
)

server <- function(input, output, session) {
  output$ui_element <- renderUI({
    "This is just some text to demonstrate. Usually there are some pictures embedded here as well,
      this is why it I use renderUI. I would like to know the position / size of this ui element"
  })
  output$plot <- renderPlot({
    plot(1:5,1:5)
  })
  output$div_size <- renderUI({
    paste(input$dimension, collapse=", ")
  })
}
# Run the application 
shinyApp(ui = ui, server = server)

字符串

相关问题