我有一個看起來像這樣的側(cè)邊欄:單擊箭頭將再次折疊側(cè)邊欄。但是,如果我單擊側(cè)邊欄外部,我想自動關(guān)閉側(cè)邊欄。這可能嗎?這是我用于切換側(cè)邊欄的腳本:<script type="text/javascript"> $(document).ready(function() { $("#sidebar").mCustomScrollbar({ theme: "minimal" }); $('#dismiss, .overlay').on('click', function() { $('#sidebar').removeClass('active'); $('.overlay').removeClass('active'); }); $('#sidebarCollapse').on('click', function() { $('#sidebar').addClass('active'); $('.overlay').addClass('active'); $('.collapse.in').toggleClass('in'); $('a[aria-expanded=true]').attr('aria-expanded', 'false'); }); }); </script>展開側(cè)邊欄的切換器圖標(biāo)(漢堡包): <div class="col-4 my-auto text-left p-1"> <button type="button" id="sidebarCollapse" class="btn"> <i class="fa fa-bars navigation-icon"></i> </button>一些CSS:#sidebar { width: 250px; position: fixed; top: 0; left: -250px; height: 100vh; z-index: 999; background: #fbcc34; color: #fff; transition: all 0.3s; overflow-y: scroll; box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.2);}#sidebar.active { left: 0;}#dismiss { width: 35px; height: 35px; line-height: 35px; text-align: center; background: #000000; position: absolute; top: 10px; right: 10px; cursor: pointer; -webkit-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s;}#dismiss:hover { background: #fff; color: #7386d5;}.overlay { display: none; position: fixed; width: 100vw; height: 100vh; background: rgba(0, 0, 0, 0.7); z-index: 998; opacity: 0; transition: all 0.5s ease-in-out;}.overlay.active { display: block; opacity: 1;}#sidebar .sidebar-header { padding: 20px; background: #000000;}因此,當(dāng)我單擊側(cè)邊欄之外的任何位置時,它應(yīng)該自動關(guān)閉側(cè)邊欄。我是否必須創(chuàng)建一個單獨(dú)的函數(shù)才能實(shí)現(xiàn)此目的?
1 回答

繁華開滿天機(jī)
TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個贊
您可以使用下面的代碼來做到這一點(diǎn):
$('body').click(function(event){
if($(event.target).attr('id') !== "sidebar" && $(event.target).attr('id') !== "sidebarCollapse") {
$('#sidebar').removeClass('active');
$('.overlay').removeClass('active');
}
});
- 1 回答
- 0 關(guān)注
- 136 瀏覽
添加回答
舉報(bào)
0/150
提交
取消