猿问

在 Shiny 中选择一个选项后,如何关闭汉堡菜单的下拉菜单

我在 R Shiny 中有一个可折叠的导航栏菜单。当菜单折叠并单击汉堡按钮时,选项出现。当我单击其中一个选项时,会(正确地)选择另一个面板,但菜单保持打开状态。


是否有可能(使用 css?)在我选择其中一个选项后立即关闭“下拉菜单”(即选项列表)?


代码如下所示:


library(shiny)


ui <- tagList(

  navbarPage(

    title = NULL, id = "navBar", collapsible = TRUE,


    tabPanel(title = "Panel1", uiOutput('panel1')),

    tabPanel(title = "Panel2", uiOutput('panel2')),

    tabPanel(title = "Panel3", uiOutput('panel3'))

  )

)


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

  output$panel1 <- renderUI({p("This is panel 1")})

  output$panel2 <- renderUI({p("This is panel 2")})

  output$panel3 <- renderUI({p("This is panel 3")})

}  


shinyApp(ui = ui, server = server)


慕婉清6462132
浏览 182回答 1
1回答

largeQ

您可以使用input$navBar(您的 id in navbarPage())在 navbarPage 上收听并通过 javascript 触发更改。&nbsp; observeEvent(input$navBar, {&nbsp; &nbsp; runjs('&nbsp; &nbsp; &nbsp; var elem = document.getElementsByClassName("navbar-collapse")[0]&nbsp; &nbsp; &nbsp; elem.setAttribute("aria-expanded", "false");&nbsp; &nbsp; &nbsp; elem.setAttribute("class", "navbar-collapse collapse");&nbsp; &nbsp; ')&nbsp; })可重现的例子:library(shiny)library(shinyjs)ui <- tagList(&nbsp; useShinyjs(),&nbsp; navbarPage(&nbsp; &nbsp; title=NULL, id = "navBar", collapsible = TRUE,&nbsp; &nbsp; tabPanel(title = "Panel1", uiOutput('panel1')),&nbsp; &nbsp; tabPanel(title = "Panel2", uiOutput('panel2')),&nbsp; &nbsp; tabPanel(title = "Panel3", uiOutput('panel3'))&nbsp; ))server <- function(input, output, session) {&nbsp; output$panel1 <- renderUI({p("This is panel 1")})&nbsp; output$panel2 <- renderUI({p("This is panel 2")})&nbsp; output$panel3 <- renderUI({p("This is panel 3")})&nbsp; observeEvent(input$navBar, {&nbsp; &nbsp; runjs('&nbsp; &nbsp; &nbsp; var elem = document.getElementsByClassName("navbar-collapse")[0]&nbsp; &nbsp; &nbsp; elem.setAttribute("aria-expanded", "false");&nbsp; &nbsp; &nbsp; elem.setAttribute("class", "navbar-collapse collapse");&nbsp; &nbsp; ')&nbsp; })}shinyApp(ui = ui, server = server)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答