使用操作按钮启用和禁用侧边栏切换按钮

时间:2018-03-14 12:59:59

标签: shiny togglebutton shinydashboard shinyjs

我正在寻找一个代码片段,我可以启用/禁用shinydashboard标题中的侧边栏切换按钮。

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- shinyUI(dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs()
  )
))

server <- shinyServer(function(input, output, session) {
  addClass(selector = "body", class = "sidebar-collapse") # Hide Side Bar
})

shinyApp(ui = ui, server = server)

让我知道是否有人可以提供帮助???

2 个答案:

答案 0 :(得分:2)

我找到了解决方法...如果有人遇到同样的问题,可以参考下面的解决方案:

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- shinyUI(dashboardPage(
  dashboardHeader(),
  dashboardSidebar( tags$head(
    tags$script(
      HTML(#code for hiding sidebar tabs 
        "Shiny.addCustomMessageHandler('manipulateMenuItem1', function(message)
        {
        var aNodeList = document.getElementsByTagName('a');

        for (var i = 0; i < aNodeList.length; i++) 
        {
        if(aNodeList[i].getAttribute('data-toggle') == message.toggle && aNodeList[i].getAttribute('role') == message.role) 
        {
        if(message.action == 'hide')
        {
        aNodeList[i].setAttribute('style', 'display: none;');
        } 
        else 
        {
        aNodeList[i].setAttribute('style', 'display: block;');
        };
        };
        }
        });"
                                                      )
    )
    )
    ),
  dashboardBody(
    useShinyjs(),
    actionButton("h1","Hide toggle"),
    actionButton("h2","Show toggle")
  )
))

server <- shinyServer(function(input, output, session) {
  observeEvent(input$h1,{
     session$sendCustomMessage(type = "manipulateMenuItem1", message = list(action = "hide",toggle = "offcanvas", role = "button"))
    })
  observeEvent(input$h2,{
    session$sendCustomMessage(type = "manipulateMenuItem1", message = list(action = "show",toggle = "offcanvas", role = "button"))
  })
})

shinyApp(ui = ui, server = server)

答案 1 :(得分:1)

如果使用shinyjs包,则可以使用快速的JavaScript行显示或隐藏侧栏切换。

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- shinyUI(dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    actionButton("hide","Hide toggle"),
    actionButton("show","Show toggle")
  )
))

server <- shinyServer(function(input, output, session) {
  observeEvent(input$hide,{
    shinyjs::runjs("document.getElementsByClassName('sidebar-toggle')[0].style.visibility = 'hidden';")
  })
  observeEvent(input$show,{
    shinyjs::runjs("document.getElementsByClassName('sidebar-toggle')[0].style.visibility = 'visible';")
  })
})

shinyApp(ui = ui, server = server)

JavaScript本身仅引用类为sidebar-toggle的第一个元素(即菜单按钮),并根据用户按下的按钮切换可见性。