如何在Shiny应用的日期选择日历中高亮标注节假日?
Shiny日期选择器高亮节假日实现方案
- 原生Shiny的
dateInput基于bootstrap-datepicker组件,无需引入额外扩展包,通过自定义JS+CSS即可实现节假日高亮效果 - 核心逻辑:预先定义节假日列表,通过JS监听日期选择器的渲染事件,为匹配到的节假日日期添加自定义样式类,再通过CSS定义高亮效果
完整可运行代码
library(shiny) library(shinythemes) function.cl<-function(df,date, d1,d2){ df <- structure( list(date = c("2021-01-01","2021-03-02","2021-04-03","2021-09-04","2021-12-05"), d1 = c(0,1,4,5,6), d2 = c(2,4,5,6,7)),class = "data.frame", row.names = c(NA, -5L)) } ui <- fluidPage( tags$head( # 自定义节假日高亮样式 tags$style(HTML(" .holiday { background-color: #ff4757 !important; color: #ffffff !important; border-radius: 4px !important; } ")), # 绑定节假日匹配逻辑 tags$script(HTML(" $(document).on('shiny:connected', function() { // 此处替换为你需要高亮的2021年节假日日期列表 const holidayList = ['2021-01-01', '2021-02-11', '2021-02-12', '2021-02-13', '2021-04-03', '2021-05-01', '2021-06-14', '2021-09-21', '2021-10-01']; // 监听日期选择器显示事件 $(document).on('show', '#date', function() { setTimeout(() => { // 遍历所有日期单元格 $('.datepicker-days td[data-date]').each(function() { const currentDate = $(this).data('date'); if (holidayList.includes(currentDate)) { $(this).addClass('holiday'); } }); }, 20); }); }); ")) ), shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE, br(), tabPanel("", sidebarLayout( sidebarPanel( uiOutput("date"), selectInput("d1", label = h4("D1"),""), selectInput("d2", label = h4("D2"),""), br(), actionButton("reset", "Reset"), ), mainPanel( )) ))) server <- function(input, output,session) { data <- reactive(function.cl()) output$date <- renderUI({ all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day") disabled <- as.Date(setdiff(all_dates, as.Date(data()$date)), origin = "1970-01-01") dateInput(input = "date", label = "Select Date", min = min(data()$date), max = max(data()$date), value = max(data()$date), format = "dd-mm-yyyy", datesdisabled = disabled) }) observe({ updateSelectInput(session, "d1", label = "D1", unique(data()$d1)) updateSelectInput(session, "d2", label = "D2", unique(data()$d2)) }) } shinyApp(ui = ui, server = server)
扩展说明
- 你可以根据实际需求修改
holidayList数组里的日期,支持任意自定义日期高亮 - 如果需要批量获取国内法定节假日,可以使用
timeDate包的holidayCN()函数直接生成对应年份的节假日列表,无需手动录入 - 修改CSS代码中的样式属性,即可调整高亮的颜色、形状、透明度等效果
- 原有日期禁用逻辑不受影响,禁用日期和节假日的样式会叠加显示
内容的提问来源于stack exchange,提问作者Antonio
相关产品推荐
相关产品推荐

