gpt4 book ai didi

javascript - 单击正文关闭侧边菜单

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:33 25 4
gpt4 key购买 nike

我希望菜单像 Medium 上的侧边菜单一样工作,当侧边菜单打开并且用户在 #sidebar-wrapper 外部单击时,侧边菜单关闭。现在,我必须单击切换 X 才能关闭菜单。

html

<a id="menu-toggle" href="#" class="toggle more navbar-brand">logo</a>
<div id="sidebar-wrapper">
<a id="menu-close" href="#" class="toggle">X</a>
</div

一些CSS

#sidebar-wrapper {
margin-left: -230px;
left: 0;
top: -20px;
width: 230px;
background: #f7f7f7;
position: fixed;
height: 120%;
overflow-y: auto;
z-index: 1000;
-webkit-transition: all 0.4s ease 0s;
-moz-transition: all 0.4s ease 0s;
-ms-transition: all 0.4s ease 0s;
-o-transition: all 0.4s ease 0s;
transition: all 0.4s ease 0s;
}

#sidebar-wrapper.active {
left: 230px;
width: 230px;
border-right: 1px solid #ccc;
-webkit-transition: all 0.4s ease 0s;
-moz-transition: all 0.4s ease 0s;
-ms-transition: all 0.4s ease 0s;
-o-transition: all 0.4s ease 0s;
transition: all 0.4s ease 0s;
}

js

<script> 
// menu close function
$("#menu-close").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
</script>

<script>
// menu open function
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
</script>

最佳答案

试试这个

$("#menu-close").click(function(e) {
e.stopPropagation();
$("#sidebar-wrapper").toggleClass("active");
});
$("#menu-toggle").click(function(e) {
e.stopPropagation();
$("#sidebar-wrapper").toggleClass("active");
});
$(document).click(function(){
if($("#sidebar-wrapper").hasClass('active')){
$("#sidebar-wrapper").removeClass("active");
}
});

DEMO

关于javascript - 单击正文关闭侧边菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23003009/

25 4 0