此问题适用于 R shiny 中的所有框类型(框、值框、选项卡框等),但我将使用简单框给出一个示例。
在我的代码中,我有很多情况在同一行中有两个或多个框。当这些框包含类似数量的信息时,高度对齐没有问题,并且使用较小的浏览器窗口动态调整此高度效果很好。
当框不包含相同数量的信息时(例如,两个相邻的表,行数不同),就会出现问题;这会导致高度排列不整齐。
我知道我可以手动设置框的高度,但是当我不知道每个框中需要显示的信息量时就会出现问题。我不想让盒子太短(并且可能会剪掉信息),也不想让盒子太高(并且使用太多屏幕空间)。但是我确实希望盒子的高度相同。
因此,是否可以提取每个框动态生成的最大高度并使用该高度强制两个框都达到该高度?
当框包含不同数量的信息时,这对我很重要,并且当屏幕调整大小时 [例如] 一个框的文本跳到两行而另一个框没有(导致高度不匹配) ).
类似问题:
R shiny Datatable: control row height to align rows of different tables
Dynamic resizing of ggvis plots in shiny apps
我为下面的 Shiny Example Number 2 提供了修改后的代码:
library(shiny)
# runExample("02_text")
ui <- fluidPage(
# App title ----
titlePanel("Shiny Text"),
# Sidebar layout with a input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Selector for choosing dataset ----
selectInput(inputId = "dataset",
label = "Choose a dataset:",
choices = c("rock", "pressure", "cars")),
# Input: Numeric entry for number of obs to view ----
numericInput(inputId = "obs",
label = "Number of observations to view:",
value = 10)
),
# Main panel for displaying outputs ----
mainPanel(
box(
# Output: Verbatim text for data summary ----
verbatimTextOutput("summary"),
title = "Verbatim",
width = 6
),
# Output: HTML table with requested number of observations ----
box(
tableOutput("view"),
title = "Table",
width = 6
)
)
)
)
server <- function(input, output) {
# Return the requested dataset ----
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"pressure" = pressure,
"cars" = cars)
})
# Generate a summary of the dataset ----
output$summary <- renderPrint({
dataset <- datasetInput()
summary(dataset)
})
# Show the first "n" observations ----
output$view <- renderTable({
head(datasetInput(), n = input$obs)
})
}
shinyApp(ui, server)
最佳答案
//使用这个函数让你的盒子等高
equalheight = function(container) {
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array(),
$el,
topPosition = 0;
$(container).each(function() {
$el = $(this);
$($el).height('auto');
topPostion = $el.position().top;
if (currentRowStart != topPostion) {
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
rowDivs.length = 0; // empty the array
currentRowStart = topPostion;
currentTallest = $el.height();
rowDivs.push($el);
} else {
rowDivs.push($el);
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
}
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});
}
$(window).load(function() {
equalheight('use your box same height class here ');
});
$(window).resize(function() {
equalheight('use your box same height class here');
});
关于R Shiny 动态框高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49129194/