Javascript 在侧边栏外单击时如何隐藏侧边栏?
我有一个边栏,看起来像这样: 单击箭头将再次折叠侧边栏。但是,如果在侧边栏外单击,我希望自动关闭侧边栏。那可能吗 这是我切换侧边栏的脚本:Javascript 在侧边栏外单击时如何隐藏侧边栏?,javascript,html,css,Javascript,Html,Css,我有一个边栏,看起来像这样: 单击箭头将再次折叠侧边栏。但是,如果在侧边栏外单击,我希望自动关闭侧边栏。那可能吗 这是我切换侧边栏的脚本: <script type="text/javascript"> $(document).ready(function() { $("#sidebar").mCustomScrollbar({ theme: "minimal" });
<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>
因此,当我单击侧边栏外的任何位置时,它应该会自动关闭侧边栏。我必须创建一个单独的函数来实现这一点吗?您可以使用下面的代码来实现这一点:
$('body')。单击(函数(事件){
if($(event.target.attr('id')!=“侧边栏”和&$(event.target.attr('id')!=“侧边栏折叠”){
$(“#侧栏”).removeClass('active');
$('.overlay').removeClass('active');
}
});
它不工作。我现在甚至无法切换侧边栏。请输入以下代码:$('body')。单击(函数(事件){console.log($(event.target.attr('id'))}然后点击你的侧边栏,检查控制台,你得到了什么消息?当你点击它的外部时,侧边栏没有关闭?我必须注释掉我以前的代码吗?请发布完整的代码,这样我才能理解。因为我甚至无法切换侧边栏打开我再次编辑了我的答案,你现在可以复制整个js脚本了。顺便说一句,我相信你已经看到了hod之所以有效,是因为我自己在我的网站上使用了它,而且效果很好。如果我知道你的HTML结构,我可以为你提供更多帮助。请尝试其他问题的解决方案:
#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;
}