单击其他div时删除一个div上的类

时间:2015-12-06 16:17:55

标签: javascript jquery html css

以下是我的HTML,

 <div class="container">
  <ul class="navbar">
    <li class="nb-link"><a>Home</a></li>

    <li class="dropdown">
      <a>CBSE</a>
      <ul class="dropdown-menu">
        <li>10th Standard</li>
        <li>12th Standard</li>
      </ul>
    </li>

    <li class="dropdown">
      <a>Engineering</a>
      <ul class="dropdown-menu">
        <li>JEE - Main</li>
        <li>JEE - Advanced</li>
      </ul>
    </li>
  </ul>

我有2个下拉菜单。当我点击一个时,它就会降下来。但当我点击另一个时,即使是在没有关闭前一个的情况下也是如此。这会产生重叠。我使用JS处理这个的方式如下

 $(document).ready(function() {
    $('.dropdown').click(function() {
        var $this = $(this);

      if ($this.children('.dropdown-menu').hasClass('open')) {
        $this.removeClass('active');
        $('.navbar').$this.children('.dropdown-menu').removeClass('open');
        $this.children('.dropdown-menu').fadeOut("fast");
      } 


        else {
          $this.addClass('active');
          $this.children('.dropdown-menu').addClass('open');
          $this.children('.dropdown-menu').fadeIn("fast");
        }

    });

});

如何使用JS实现功能,以便在单击新下拉列表时关闭上一个下拉列表?此外,当点击页面上的任何位置时,下拉列表应该关闭?

2 个答案:

答案 0 :(得分:2)

可以尝试这个

$(document).ready(function() {
    $('.dropdown').click(function() {
        var $this = $(this);
        $('.dropdown').not($this).removeClass('active')
        $('.dropdown-menu').not($this.find('.dropdown-menu')).removeClass('open');
        $this.toggleClass('active');
        $this.find('.dropdown-menu').toggleClass('open');
    });
});

Working Demo

如果选择器不是目标,则可以使用此功能

// function for if selectors not target
function actionwindowclick(e , selector , action){
            if (!$(selector).is(e.target) // if the target of the click isn't the container...
                && $(selector).has(e.target).length === 0) // ... nor a descendant of the container
            {
            action();
        }
}

你可以在像这样的窗口点击事件中使用它

$(window).on('click', function(e){
     actionwindowclick(e , ".dropdown , .dropdown-menu" , function(){
         $('.dropdown').removeClass('active')
         $('.dropdown-menu').removeClass('open');
     });
});

Working Demo

  

注意:我认为您可能需要   event.stopPropagation()   当你试图点击.dropdown-menu本身

$('.dropdown-menu').click(function(e) {
   e.stopPropagation()
});

答案 1 :(得分:-1)

尝试:
    $(document).ready(function() {
$('.dropdown').click(function() {
var $this = $(this);
$this.children('.dropdown-menu').toggleClass('open');
if ($this.children('.dropdown-menu').hasClass('open')) {
$this.removeClass('active');
$this.children('.dropdown-menu').fadeOut("fast");
}
else {
$this.addClass('active');
$this.children('.dropdown-menu').fadeIn("fast");
}
});
});

相关问题