如何关闭除了div之外的任何地方的div?

时间:2018-05-28 18:20:50

标签: jquery html css

我正在创建一个'抽屉'单击条形图中的任何链接时会打开,并根据单击的链接更改抽屉中的内容。

尽管我已经研究过这一点,但现在我已经陷入了困境。我发现很难找到适用于我当前设置的解决方案。我想设置它以便点击其他任何地方的抽屉'淡出。任何人都可以了解我如何通过目前的设置实现这一目标吗?

提前致谢!



$('.filters-toolbar__drop-down:gt(0)').hide();
$('.filters-toolbar__drop-down-wrapper').hide();

$('.filters-toolbar').on('click', 'a', function() {
  $('.current').not($(this).closest('li').addClass('current')).removeClass('current');
  var $this = $(this);
  $('.filters-toolbar__drop-down-wrapper').fadeIn('slow');
  $('body').addClass('filter-open');

  // fade out all open subcontents
  var visibleElements = $('.filters-toolbar__drop-down:visible');
  if (visibleElements.length <= 0) {
    $('.filters-toolbar__drop-down[id=' + $this.data('id') + ']').fadeIn('slow');
  } else {
    visibleElements.fadeOut('slow', function() {
      $('.filters-toolbar__drop-down[id=' + $this.data('id') + ']').fadeIn('slow');
    });
  }
});
&#13;
.filters-toolbar-wrapper {
  margin-bottom: 0;
  width: 100%;
}

.filters-toolbar__item {
  padding: 0 50px;
   display: inline-block;
}

.filters-toolbar__drop-down-wrapper {
  background-color: grey;
  border-bottom: 1px solid #000;
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 200px;
}

.filters-toolbar__drop-down {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters-toolbar-wrapper">
  <div class="filters-toolbar">

    <div class="filters-toolbar__item">
      <a href="#" data-id="filter1">Type</a>
    </div>
    
    <div class="filters-toolbar__item">
      <a href="#" data-id="filter2">Color</a>
    </div>

    <div class="filters-toolbar__item">
      <a href="#" data-id="filter3">Sorty by</a>
    </div>
    
  </div>
</div>

<div class="filters-toolbar__drop-down-wrapper">
  <div id="filter1" class="filters-toolbar__drop-down by-type">
    Type Dropdown
  </div>
  <div id="filter2" class="filters-toolbar__drop-down by-color">
    Color Dropdown
  </div>
  <div id="filter3" class="filters-toolbar__drop-down sort-by">
    Sort Dropdown
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

You can listen for click on the document or window and inside the listener function you can compare the id or any other attribute that you have on drawer.

If it doesn't match with the drawer attribute simply close the drawer.

document.addEventListener('click', function(event) {
// You can choose any attribute available on drawer
// Instead of id
if (event.target.id != 'drawer') {

  `$("#drawer").fadeOut();`
}
});

You should add this listener inside your link click function and you can remove it later after fadeOut