为了账号安全,请及时绑定邮箱和手机立即绑定

单击侧边栏外部时如何隐藏侧边栏?

单击侧边栏外部时如何隐藏侧边栏?

LEATH 2023-09-25 15:51:32
我有一个看起来像这样的侧边栏:单击箭头将再次折叠侧边栏。但是,如果我单击侧边栏外部,我想自动关闭侧边栏。这可能吗?这是我用于切换侧边栏的脚本:<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>展开侧边栏的切换器图标(汉堡包): <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;}因此,当我单击侧边栏之外的任何位置时,它应该自动关闭侧边栏。我是否必须创建一个单独的函数才能实现此目的?
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

您可以使用下面的代码来做到这一点:


$('body').click(function(event){

   if($(event.target).attr('id') !== "sidebar" && $(event.target).attr('id') !== "sidebarCollapse") {

     $('#sidebar').removeClass('active');

     $('.overlay').removeClass('active');

   }

});


查看完整回答
反对 回复 2023-09-25
  • 1 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信