我希望菜单在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>
答案 0 :(得分:2)
试试这个
$("#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");
}
});
答案 1 :(得分:1)
使用stopPropagation防止事件冒泡
$("#menu-close").click(function(e) {
e.stopPropagation();
$("#sidebar-wrapper").toggleClass("active");
});
$(document).click(function(e) {
$("#sidebar-wrapper").toggleClass("active");
});