R Shiny启用BS5主题后HTML格式Tooltip失效的解决方法
解决Shiny中BS5主题下Tooltip HTML格式失效问题
原本以下代码可实现点击触发且HTML格式正常的Tooltip:
library(shiny) library(bslib) ui <- fluidPage( # theme = bs_theme(version = 5, bootswatch = "pulse"), tags$head(tags$script( " $(document).ready(function(){ $('[data-toggle=\"tooltip\"]').tooltip({ trigger: 'click' }); }); ")), selectInput( inputId = "action", label = tags$span(tags$i(`data-toggle` = "tooltip", `data-placement` = "right", `data-html` = TRUE, title = "This is:<br>My <b>tooltip</b> text!", icon("circle-info")), "More label text."), choices = c(1,2,3), selected = 1 ) ) server <- function(input, output, session) { } shinyApp(ui, server)
但启用bs_theme()调用后,Tooltip中的HTML格式会失效,这确实是Bootstrap 5默认的内容清理机制(sanitization)导致的。要解决这个问题,需要调整Tooltip的初始化配置,并适配BS5的属性命名规范,修改后的完整代码如下:
library(shiny) library(bslib) ui <- fluidPage( theme = bs_theme(version = 5, bootswatch = "pulse"), tags$head(tags$script( " $(document).ready(function(){ $('[data-bs-toggle=\"tooltip\"]').tooltip({ trigger: 'click', sanitize: false }); }); ")), selectInput( inputId = "action", label = tags$span(tags$i(`data-bs-toggle` = "tooltip", `data-bs-placement` = "right", `data-bs-html` = TRUE, title = "This is:<br>My <b>tooltip</b> text!", icon("circle-info")), "More label text."), choices = c(1,2,3), selected = 1 ) ) server <- function(input, output, session) { } shinyApp(ui, server)
关键修改说明:
- 适配BS5属性命名:将原有的
data-toggle、data-placement、data-html分别改为data-bs-toggle、data-bs-placement、data-bs-html,这是Bootstrap 5组件属性的统一命名规则。 - 关闭内容清理:在Tooltip的初始化配置中添加
sanitize: false,禁用BS5默认的内容清理机制,从而保留Tooltip中的HTML格式。 - 保留点击触发逻辑:继续保留
trigger: 'click'配置,维持点击触发Tooltip的交互方式。
内容的提问来源于stack exchange,提问作者SimonSimon
相关产品推荐
相关产品推荐

