简体   繁体   English

响应站点的导航菜单的jquery click事件冲突

[英]Conflicting jquery click events for navigation menu of responsive site

I am implementing a mobile navigation menu and I want to capture the click event on the non-menu area in order to close the menu. 我正在实现一个移动导航菜单,我想捕获非菜单区域的click事件以关闭菜单。

//#1 click event - opening menu when user clicks on button
$('.mobile-menu-toggler').on('click', function(){
   $('.navi-mobile').addClass('nav-mobile-open');
   $('.site-page').addClass('site-page-open');
});

//#2 click event - hide menu when user clicks on outside nav
$(document).on('click', function(e){
    var obj = $('.navi-mobile')
    var nav_open = obj.hasClass('nav-mobile-open');
    var ext = (e.target == obj[0]);

    if (nav_open && !ext) {
        e.preventDefault();
        console.log('hide menu')
    }
});

The problem is that event #2 gets fired at the same time as #1 when the user opens the nav. 问题是用户打开导航时,事件#2与事件#1同时被触发。 And the conditions in #2 are allowing the hide action to take place. #2中的条件允许执行隐藏操作。

One valid approach is to prevent the effect of #2 when the event #1 is fired. 一种有效的方法是在触发事件#1时防止#2的影响。 You can do it using stopPropagation function in #1 您可以使用#1中的stopPropagation函数来完成此操作

//#1 click event - opening menu when user clicks on button
$('.mobile-menu-toggler').on('click', function(e){
   e.stopPropagation();
   $('.navi-mobile').addClass('nav-mobile-open');
   $('.site-page').addClass('site-page-open');
});

Also you can check if the clicked dom element has a parent with class nav-mobile-open, and stop the event if this condition is true. 您也可以检查所单击的dom元素是否具有带有nav-mobile-open类的父级,如果此条件为true,则停止事件。

var nav_open = obj.hasClass('nav-mobile-open');
if(obj.parents('.nav-mobile-open').length) nav_open = true;

Regards. 问候。

jQuery .stopPropagation Documentation jQuery .stopPropagation文档

Try adding a stopPropagation() function to your document.click declaration 尝试在文档中添加stopPropagation()函数。

//#2 click event - hide menu when user clicks on outside nav
$(document).on('click', function(e){

    e.stopPropagation(); // HERE

    var  obj = $('.navi-mobile')
    var nav_open = obj.hasClass('nav-mobile-open');
    var ext = (e.target == obj[0]);

    if (nav_open && !ext) {
        e.preventDefault();
        console.log('hide menu')
    }
});

here 'sa link for more info 是更多信息的链接

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

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