簡體   English   中英

用jQuery切換按鈕

[英]Toggle a button With jquery

當窗口變得太小時,我進行了一些媒體查詢以隱藏側邊菜單。 問題是我無法再次切換菜單,因為它是在CSS上硬編碼的。

因此,我嘗試單擊該按鈕以隱藏側邊欄。 但是在我調整大小時,它會多次單擊。

當窗口小於991px時,我該怎么做才能隱藏側邊菜單,但單擊按鈕后仍然可以再次顯示?

 $(window).resize(function() { var width = $(document).width(); if (width < 991) { $('#sidebar-btn').click(); } }); $('#sidebar-btn').click(function() { $('#sidebar').toggle('visible'); $('.content-wrapper, .full-page-wrapper').toggleClass('content-wrapper full-page-wrapper'); }); 
 #sidebar { background: #fafafa; border-right: 2px solid #e5e5e5; width: 200px; height: 100%; display: block; position: absolute; top: 0; overflow-x: hidden; transition: left 1s ease; } @media screen and (max-width: 991px) { #sidebar { left: -200px !important; } .content-wrapper { background: #fff; margin-left: 0; min-height: 100vh; padding: 1rem 1.5rem; margin-bottom: 70px; transition: all 1s ease; } } 

您可以有一個標志變量,以保持側欄的隱藏/可見狀態。

 var sidebarIsVisible = true; $(window).resize(function() { var width = $(document).width(); if (width < 991) { if (sidebarIsVisible) { // Will happen only once now $('#sidebar-btn').click(); sidebarIsVisible = false; } else { if (!sidebarIsVisible) { // Make visible if width is greater than 991 and sidebar is invisible $('#sidebar-btn').click(); sidebarIsVisible = true; } } } }); 

為什么當width小於991使用hide() jQuery只隱藏#sidebar

$(window).resize(function() {
  var width = $(document).width();
  if (width < 991) {
    $('#sidebar').hide();
  }else{
    $('#sidebar').show();
  }
});

992px及以上-顯示#sidebar並隱藏#sidebar-btn

#sidebar{
    display: block;
}
#sidebar-btn{
    display: none;
}

對於991px及以下的像素-隱藏#sidebar並顯示#sidebar-btn

@media screen and (max-width: 991px) {
    #sidebar{
        display: none;
    }
    #sidebar-btn{
        display: block;
    }
}

現在,使用#sidebar-btn單擊上的切換側欄

$('#sidebar-btn').click(function (){
    $('#sidebar').toggle();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM