【问题标题】:How to close navigation with outside click?如何通过外部点击关闭导航?
【发布时间】:2017-03-14 06:28:02
【问题描述】:

我想在窗口的其余部分检测菜单类 .tab-nav-menu 之外的点击,并添加一个事件以关闭具有类似关闭动画的菜单。

// Menu
jQuery(function($) {
    $('.header-menu-toggle').on('click', function(e){
        e.preventDefault();
        $('.tab-nav-menu >ul >li').animate({
            opacity: 0
        }, 200).animate({
            bottom: '-25px'
        }, 50);

        if($('.tab-nav-menu').hasClass('tab-invisible') ){
            $('.tab-nav-menu').css({'right':'-1em'});
            $('.tab-nav-menu').removeClass('tab-invisible').addClass('tab-visible');
            $(this).find('.burg').addClass('activeBurg');
        }
        else{
            $('.tab-nav-menu').css({'right':'-100%'});
            $('.tab-nav-menu').removeClass('tab-visible').addClass('tab-invisible');
            $(this).find('.burg').removeClass('activeBurg');
        }
        var delay = 600;
        var duration = 400;
        if( $(".header-navigation-menu").hasClass("strip-header-menu") ){
            delay = 250;
        }
        $('.tab-nav-menu >ul >li').each(function(){
            $(this).delay(delay).animate({
                opacity: 1,
                bottom: 0,
            }, duration);
            delay += 150;
        });
    })
});

感谢您的帮助

【问题讨论】:

  • 我们通过在<body> 标记上添加一个点击处理程序并调用一个函数来实现这一点,该函数实质上是从菜单层次结构中的菜单和子菜单项中删除一个类。我们不使用.animate() 之类的,我们使用直接CSS 来显示/隐藏菜单,我们只是调整菜单项上的类。
  • 您仍然可以使用动画并遵循上述建议,只需创建一个主体点击处理程序,它会在您的菜单中找到相关的类,处理它们,并相应地为它们设置动画

标签: javascript jquery


【解决方案1】:

一个简化的“外部点击”jQuery 脚本:

$(document).ready(function () {

  $(document).on('click', function (e) {
    var clickedEl = $(e.target);
    var outsideClicker = $('#clicker');

    if ( !(clickedEl.is(outsideClicker)
 || outsideClicker.has(clickedEl).length > 0) ) { // I flipped this so you can just omit the else
      console.log('I clicked outside the target!'); // do whatever you need to do here-- maybe call a function that closes the menu...
    } else {
      console.log('all good'); // if you don't have an else just get rid of this
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

  <h1> A title </h1>
  <p> A paragraph and a <b id="clicker">thing <span>to</span> click </b></p>

</div>

您可以根据自己的目的进行推断。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2018-11-11
    相关资源
    最近更新 更多