【发布时间】:2018-07-30 14:05:55
【问题描述】:
问题
我使用下面的代码通过 javascript 动态更改 shinydashboard::box 的大小。原则上这可以正常工作,但是框内来自plotOutput 的图像在大小方面无法正确重新渲染。也就是说,无论周围box 的大小如何,绘图宽度都保持不变。有趣的是,当我在 Chrome 中使用 Inspect 查看源代码时,图形突然被调整大小。
截图
问题
我需要如何调整我的代码以调整 input$cols 更改时的绘图大小?值得一提的是,在我的真实代码中,盒子的内容是通过模块动态呈现的。因此,我几乎无法控制 renderPlot 函数本身。由于图像在我“检查”后立即调整大小,我希望有一个我可以调用的 javascript 函数,它可以为我完成这项工作。
代码
library(shiny)
library(shinydashboard)
library(shinyjs)
library(glue)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(selectInput("cols", NULL, c(2, 3, 4, 6, 12), 4)),
dashboardBody(
useShinyjs(),
div(
box(solidHeader = TRUE,
title = "Box",
width = 4,
status = "info",
sliderInput("sld", "n:", 1, 100, 50),
plotOutput("plt")
), id = "box-parent")
))
server <- function(input, output) {
observe({
cols <- req(input$cols)
runjs(code = glue('var $el = $("#box-parent > :first");',
'$el.removeClass(function (index, className) {{',
'return (className.match(/(^|\\s)col-sm-\\d+/g) || []).join(" ")',
'}});',
'$el.addClass("col-sm-{cols}");'))
})
output$plt <- renderPlot(plot(rnorm(input$sld), rnorm(input$sld)))
}
shinyApp(ui, server)
【问题讨论】:
-
我找到了使用
$(window).trigger('resize')的解决方案。这种方法有什么我可能会忽略的吗? -
你可能会放心。我一般先在
plotOutput()函数中尝试width = "100%",让CSS调整宽度。如果这不起作用,触发调整大小可能是要走的路。 -
谢谢,用
width=100%试过了,但没用,所以我还是用trigger吧。
标签: r shiny shinydashboard