如何修改bslib侧边栏切换按钮在展开/收起状态的文本?
实现bslib侧边栏切换按钮的文本动态切换
要实现侧边栏展开时按钮显示“Close Options”、收起时显示“Options”,只需借助bslib自带的sidebar-open状态类,结合CSS伪元素的content属性即可完成,无需额外JS。
修改步骤:
- 移除原代码中固定设置
content: 'Options'的::after规则 - 新增两个针对不同侧边栏状态的
::after规则,分别设置对应文本
修改后的完整代码:
library(bslib) library(shiny) library(ggplot2) custom_sidebar <- function(ui_content, ...) { div( class = "custom-sidebar", page_sidebar( ..., tags$head(tags$style(HTML( " /* Style the toggle button */ .custom-sidebar .bslib-sidebar-layout > .collapse-toggle { padding: 15px 10px; background-color: #007398; position: absolute; border-radius: 0 5px 5px 0; writing-mode: vertical-rl; text-orientation: mixed; height: auto; z-index: 1000; display: flex; align-items: center; justify-content: center; transition: all 0.3s; top: 100px; /* Position from top */ right: -40px; /* Position on the right of sidebar */ } /* When sidebar is closed */ .custom-sidebar .bslib-sidebar-layout:not(.sidebar-open) > .collapse-toggle { left: 0; right: auto; /* Reset right position when closed */ } /* Style the toggle icon */ .custom-sidebar .bslib-sidebar-layout > .collapse-toggle > .collapse-icon { fill: white !important; margin-bottom: 10px; } /* 侧边栏收起时显示Options */ .custom-sidebar .bslib-sidebar-layout:not(.sidebar-open) > .collapse-toggle::after { content: 'Options'; color: white; font-size: 1.1em; text-transform: uppercase; letter-spacing: 1px; margin-top: 10px; } /* 侧边栏展开时显示Close Options */ .custom-sidebar .bslib-sidebar-layout.sidebar-open > .collapse-toggle::after { content: 'Close Options'; color: white; font-size: 1.1em; text-transform: uppercase; letter-spacing: 1px; margin-top: 10px; } /* Adjust main content margins */ .custom-sidebar .bslib-sidebar-layout > .main { margin-left: 300px; transition: margin-left 0.3s; width: calc(100% - 300px); } .custom-sidebar .bslib-sidebar-layout:not(.sidebar-open) > .main { margin-left: 0; width: 100%; } .custom-sidebar .bslib-sidebar-layout>.sidebar { margin-left: 20px; } " ))), ui_content ) ) } ui <- custom_sidebar( title = "Example dashboard", sidebar = sidebar( open = FALSE, # 初始状态为收起 varSelectInput("var", "Select variable", mtcars) ), card( full_screen = TRUE, card_header("My plot"), plotOutput("p") ) ) server <- function(input, output) { output$p <- renderPlot({ ggplot(mtcars) + geom_histogram(aes(!!input$var)) }) } shinyApp(ui, server)
关键CSS说明:
.bslib-sidebar-layout:not(.sidebar-open):匹配侧边栏收起状态的容器,此时按钮的::after伪元素显示"Options".bslib-sidebar-layout.sidebar-open:匹配侧边栏展开状态的容器,此时按钮的::after伪元素显示"Close Options"- bslib会自动在侧边栏切换时为容器添加/移除
sidebar-open类,无需手动控制
内容的提问来源于stack exchange,提问作者umair durrani
相关产品推荐
相关产品推荐

