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

如何为pickerInput的.dropdown-menu.open添加slideDown或fadeInDown动画?

给shinyWidgets的pickerInput添加下拉展开动画

当然可以实现类似dropdown组件的平滑展开/收起动画,下面提供两种可行的方法:

方法1:利用bootstrap-select原生配置

pickerInput基于bootstrap-select组件,我们可以通过options参数直接配置动画效果,和你提到的dropdown组件逻辑一致:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  # 引入animate.css动画库,fadeInDown这类动画依赖它
  tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"),
  
  pickerInput(
    inputId = "countryid1",
    label = "Select:",
    choices = c("Brazil", "Argentina", "Colombia", "Paraguay", "Bolivia", "Trinidad and Tobago"),
    selected = "Paraguay",
    options = list(
      # 配置展开动画为fadeInDown,时长300ms
      show = list(effect = "fadeInDown", duration = 300),
      # 配置收起动画为fadeOutUp,时长300ms
      hide = list(effect = "fadeOutUp", duration = 300)
    )
  )
)

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

shinyApp(ui, server)

方法2:自定义JS+CSS控制动画

如果原生配置不满足需求,也可以通过监听组件事件手动添加动画类:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"),
  
  pickerInput(
    inputId = "countryid1",
    label = "Select:",
    choices = c("Brazil", "Argentina", "Colombia", "Paraguay", "Bolivia", "Trinidad and Tobago"),
    selected = "Paraguay"
  ),
  
  tags$script(HTML('
    // 监听下拉展开事件
    $("#countryid1").on("show.bs.select", function() {
      $(this).next(".dropdown-menu").addClass("animate__animated animate__fadeInDown");
    });
    // 监听下拉收起事件
    $("#countryid1").on("hide.bs.select", function() {
      var $menu = $(this).next(".dropdown-menu");
      $menu.addClass("animate__animated animate__fadeOutUp");
      // 动画结束后移除类,避免影响下次动画
      setTimeout(() => {
        $menu.removeClass("animate__animated animate__fadeInDown animate__fadeOutUp");
      }, 300);
    });
  '))
)

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

shinyApp(ui, server)

说明:

  • 两种方法都需要引入animate.css,因为fadeInDown、fadeOutUp这些动画类是该库提供的,和dropdown组件使用的是同一套资源。
  • 方法1更简洁,利用组件原生能力;方法2灵活性更高,可自定义更复杂的动画逻辑。

内容的提问来源于stack exchange,提问作者neves

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:15:13