简体   繁体   English

div启用复选框,但在div之外时检测到单击以关闭

[英]Div toggle on checkbox but detect click when outside of the div to toggle off

I'm trying to make my burger menu detect click when outside of the menu (.NavMenu) and change the hamburger checkbox back to unselected. 我试图使我的汉堡菜单在菜单(.NavMenu)外部时检测到单击,并将“汉堡”复选框更改回未选中状态。

I've tried using event.stopPropagation(); 我试过使用event.stopPropagation(); and trying to detect clicks in the document but my javascript knowledge is really limited so I am either not being able to show .NavMenu at all or .NavMenu closes when clicked outside but the hamburger menu stays as if it was open (X). 并尝试检测文档中的点击,但是我的JavaScript知识真的很有限,所以我要么无法完全显示.NavMenu,要么在外面单击时.NavMenu关闭,但汉堡菜单却像打开时一样(X)保留。

Can anyone help me with how to get the menu to close when clicked outside of the div that will also trigger the checkbox? 任何人都可以在div外部单击时关闭菜单(也将触发该复选框),如何帮助我关闭菜单?

http://jsfiddle.net/s9ndequ2/ http://jsfiddle.net/s9ndequ2/

You can achieve that by giving some id or class to the main div which will holding your page contents and then in script you can detect whether click has been performed inside that div or not : 您可以通过为将保存页面内容的主div赋予一些id或class来实现,然后在脚本中可以检测是否在该div内进行了点击:

Considering your main div has class mainDiv you can add below snippet to your script to achieve what you have asked for : 考虑到您的主要div具有mainDiv类,您可以在脚本中添加以下代码片段,以实现所需的功能:

$(".mainDiv").click(function(){
    if($('#burger').is(':checked'))
    $('#burger').click();
}); 

Try this at your fiddle: 试试看:

$('#burger').click(function(event) {
 event.stopPropagation();
 if( $(this).is(':checked')) {
    $(".NavMenu").show();       
 } else {
    $(".NavMenu").hide();
 }
});  

$('body').click(function() {
  if ( $('#burger').is(':checked')) {
    $(".NavMenu").hide();
    $( "#burger" ).prop( "checked", false );
  }
})

$('.NavMenu').click(function(event) {
  event.stopPropagation();
})

http://jsfiddle.net/s9ndequ2/2/ http://jsfiddle.net/s9ndequ2/2/

Add id 'burgerMenu' on div with class='NavMenu'. 在div上使用class ='NavMenu'添加id'burgerMenu'。

And modify your JavaScript as 并将您的JavaScript修改为

$('#burger').click(function() {
     if( $(this).is(':checked')) {
        $(".NavMenu").show();       
     } else {
        $(".NavMenu").hide();
     }
    });  
    $('body').click(function(event){
      removeBurger(event)
    })
    //this detects that user has clicked outside the menu
    function removeBurger(e){
      var targ;
      if (!e) {
          var e = window.event;
      }
      if (e.target) {
          targ=e.target;
      } else if (e.srcElement) {
          targ=e.srcElement;
      }
      if(targ.id!="burgerMenu" && targ.id!="burger"){
        if ( $('#burger').is(':checked')) {
        $(".NavMenu").hide();
        $( "#burger" ).prop( "checked", false );
      }
    }
    }

Hope this will help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM