当您在容器外部单击时,关闭汉堡菜单 [英] Close the hamburger menu when you click outside of container

查看:79
本文介绍了当您在容器外部单击时,关闭汉堡菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个非常简单的汉堡包菜单.我正在使用jQuery来单击汉堡包时将其切换为打开和关闭状态.但是我希望用户单击div或菜单之外的任何位置时都可以将其关闭.

I want to have a very simple hamburger menu. I'm using jQuery to toggle it to open and close when the hamburger is clicked. But I would like for the user to be able to close it when they click anywhere outside of the div or menu.

jsfiddle 是我写的.不要介意样式.

The jsfiddle is what I have written out. Don't mind the styling.

我想使用类似的东西

$(window).on('click', function(){
    $('.responsive-menu').removeClass('expand');
})

但是添加了这些,我什至无法打开菜单.请帮忙.谢谢!

But with that added, I cannot even open the menu. Please help. Thank you!

推荐答案

技巧是检查单击的元素是否具有父.responsive-menu.menu-btn.

The trick is to check if the element clicked has a parent .responsive-menu or .menu-btn.

如果两者都不存在且菜单已展开,请切换!

If it has'n any of the two and the menu is expanded, toggle!

更新了小提琴

$(document).on("click", function(e){
  if( 
    $(e.target).closest(".responsive-menu").length == 0 &&
    $(".responsive-menu").hasClass("expand") &&
    $(e.target).closest(".menu-btn").length == 0
  ){
    $('.responsive-menu').toggleClass('expand');
  }
});

这篇关于当您在容器外部单击时,关闭汉堡菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆