You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态调整bslib/Shiny应用的font_scale实现字体大小切换?

解决Shiny应用中动态切换字体大小的问题

原代码中通过bs_global_set更新主题不会生效,因为Shiny的UI在启动时已基于初始主题生成静态HTML,运行时更新全局主题无法触发UI重新渲染。以下是两种可行的实现方案:

方案一:使用响应式主题动态渲染UI

将核心UI内容放在uiOutput中,让其响应主题变化重新渲染,确保每次切换字体大小都会生成基于新主题的HTML。

完整代码:

library(shiny)
library(bslib)

ui <- fluidPage(
    shiny::radioButtons(
        inputId="pref",
        label="Text Size:",
        selected = "standard",
        choiceNames = c("Small", "Standard", "Large"),
        choiceValues = c("small", "standard", "large")
    ),
    uiOutput("main_content")
)

server <- function(input, output, session) {

    text_scale <- reactive({
        switch(input$pref,
               "small" = 0.8,
               "standard" = 1.0,
               "large" = 1.2)
    })

    # 创建响应式主题
    current_theme <- reactive({
        bs_theme(font_scale = text_scale())
    })

    # 动态渲染UI内容
    output$main_content <- renderUI({
        bslib::page_sidebar(
            title = "Font Size",
            fillable = FALSE,
            theme = current_theme(),
            shiny::markdown(
                "## Sample Markdown\n\nThis is *italic* and **bold** text. The size changes with your selection."
            )
        )
    })

}

shinyApp(ui = ui, server = server)

方案二:直接修改Bootstrap CSS变量(更轻量)

Bootstrap的字体大小由CSS变量控制,通过动态注入CSS修改这些变量,无需重新渲染整个UI,性能更优。

完整代码:

library(shiny)
library(bslib)

ui <- bslib::page_sidebar(
    title = "Font Size",
    fillable = FALSE,
    sidebar = bslib::sidebar(
        shiny::radioButtons(
            inputId="pref",
            label="Text Size:",
            selected = "standard",
            choiceNames = c("Small", "Standard", "Large"),
            choiceValues = c("small", "standard", "large")
        )
    ),
    tags$head(uiOutput("font_size_style")),
    shiny::markdown(
        "## Sample Markdown\n\nThis is *italic* and **bold** text. The size changes with your selection."
    )
)

server <- function(input, output, session) {

    text_scale <- reactive({
        switch(input$pref,
               "small" = 0.8,
               "standard" = 1.0,
               "large" = 1.2)
    })

    output$font_size_style <- renderUI({
        scale <- text_scale()
        # 按比例调整基础字体及各级标题字体大小
        tags$style(
            paste0("
                :root {
                    --bs-body-font-size: ", scale, "rem;
                    --bs-h1-font-size: calc(2.5rem * ", scale, ");
                    --bs-h2-font-size: calc(2rem * ", scale, ");
                    --bs-h3-font-size: calc(1.75rem * ", scale, ");
                }
            ")
        )
    })

}

shinyApp(ui = ui, server = server)

内容的提问来源于stack exchange,提问作者Karsten W.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:47:07