r - 单击退出时隐藏 Shiny 仪表板上的下拉选项

标签 r shiny shinydashboard

当我单击该字段外部时,我想退出一个选项(menuSubItem),但当我单击外部时该选项不会消失。我尝试了使用 CSS 的解决方案,但没有奏效!我的代码:

library(shiny)
library(shinydashboard)

header <- dashboardHeader(title = "Dashboard", titleWidth = 320)

sidebar <- dashboardSidebar(
  width = 320,
  sidebarMenu(
    menuItem(
      text = "A1"
    ),
    menuItem(
      text = "A2",
      menuSubItem(
        text = "AA1"
      ),
      menuSubItem(
        text = "AA2"
      ), 
      menuSubItem(
        text = "AA3"
      )
    )
  )
)

body <- dashboardBody()

ui <- dashboardPage(header = header, sidebar, body)

server <- function(input, output) {
  
}

shinyApp(ui, server)

我想在 A2 外部单击,并在单击完成后让它 (A2) 关闭下拉菜单。

我尝试在正文中插入此代码:

body <- dashboardBody(

  HTML(
  "<script>

  $(function() {

    $(document).on('click', function() {
      $('.skin-blue .treeview-menu>li>a').slideUp();
    });
 
  });

  </script>"
  )

)

但不工作。

最佳答案

我们可以为 menuItem 提供一个 id 并移除 css 类 menu-open:

library(shiny)
library(shinydashboard)

header <- dashboardHeader(title = "Dashboard", titleWidth = 320)

sidebar <- dashboardSidebar(width = 320,
                            sidebarMenu(
                              menuItem(text = "A1"),
                              menuItem(
                                text = "A2",
                                id = "A2ID",
                                menuSubItem(text = "AA1"),
                                menuSubItem(text = "AA2"),
                                menuSubItem(text = "AA3")
                              )
                            ))

body <- dashboardBody(tags$script(
  HTML(
    "$(document).on('shiny:connected', function(event) {
        $(document).on('click', function(evt) {
          if($(evt.target).closest('#sidebarItemExpanded > ul > li.treeview').length)
            return;
          var el = document.getElementById('A2ID');
          el.style.display = 'none';
          el.classList.remove('menu-open');
      });
    });"
  )
))

ui <- dashboardPage(header = header, sidebar, body)

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

shinyApp(ui, server)

result

一些相关链接:

jQuery click anywhere in the page except on 1 div

https://github.com/rstudio/shinydashboard/issues/347

关于r - 单击退出时隐藏 Shiny 仪表板上的下拉选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73544823/

相关文章:

r - 如何查看 `dplyr::collect` 方法的帮助?

r - 从数据框中的列中添加和减去值

r - dplyr() 中的非标准评估和 quasiquotation 未按(天真)预期工作

css - 如何修改 Shiny 默认 CSS 来改变 sidebarPanel 的背景颜色?

html - 为什么shinydashboard 将 numericInput 的 Angular 从圆形更改为 90 度?

R:data.table 计数 !NA 每行

r - Shiny :根据选择更新 selectizeInput 选项

r - 如何更改 R Shiny 应用程序中图标的颜色?

css - 删除 dashboardSidebar 中 splitLayout 中列之间的间隙

R Shiny 。没有适用于 'mutate' 的方法应用于类 "c('reactiveExpr', 'reactive' , 'function' ) 的对象"