如何在页面顶部创建固定tabPanel横幅并使下方内容可滚动?
实现Shiny页面中tab标签栏固定+内容区域滚动的效果
要实现tab标签栏固定在页面顶部、仅内容区域滚动的效果,直接通过自定义CSS调整元素定位即可,以下是修改后的完整可运行代码:
library("shiny") library("stringi") txt <- paste(sapply(seq_len(100), function(x){ p <- shiny::tags$p(stringi::stri_rand_lipsum(1)) return(as.character(p)) }), collapse = "") ui = navbarPage(title = "Navbar example", position = c("fixed-top"), id = "navbar", # 添加自定义CSS tags$style(HTML(" /* 给body设置顶部内边距,避开固定的navbar */ body { padding-top: 50px; } /* 固定tab标签栏 */ .fixed-tabset .nav-tabs { position: fixed; top: 50px; /* 对应navbar的高度,确保标签栏接在navbar下方 */ left: 0; right: 0; background-color: #fff; /* 背景色覆盖下方内容 */ border-bottom: 1px solid #ddd; z-index: 1000; } /* 设置内容区域的布局,让它可滚动 */ .fixed-tabset .tab-content { margin-top: 80px; /* 避开固定的标签栏,值要大于等于标签栏高度 */ overflow-y: auto; height: calc(100vh - 80px); /* 内容区域占满剩余视口高度 */ } ")), tabPanel(title = "tab 1", # 给tabsetPanel添加自定义类 tabsetPanel(id = "id1", class = "fixed-tabset", tabPanel(title = "A", HTML(txt) ), tabPanel(title = "B", HTML(txt) ) )), tabPanel(title = "tab 2", tabsetPanel(id = "id2", class = "fixed-tabset", tabPanel(title = "C", HTML(txt) ), tabPanel(title = "D"), tabPanel(title = "E", HTML(txt) ) )) ) server = shinyServer(function(input, output) { }) shinyApp(ui, server)
关键说明
- 给
tabsetPanel添加了fixed-tabset类,方便CSS精准定位; - 通过
position: fixed把tab标签栏固定在navbar下方,设置背景色避免被内容滚动覆盖; - 内容区域设置
overflow-y: auto开启垂直滚动,用calc(100vh - 80px)让内容区域自动适配剩余视口高度; - 用body的
padding-top替代原有的多个br(),布局更规范可控。
内容的提问来源于stack exchange,提问作者nimliug
相关产品推荐
相关产品推荐

