Toggle script problems how can I fix this in pure JavaScript? No jQuery

时间:2018-01-23 19:43:19

标签: javascript

I have made this script and I design it in a way when you click any where outside of the div the div should disappear but I notice that when you click on the div it self it disappear as well. How can I prevent that from occurring I only want it to work by clicking any where out side the div to make the div disappear not by clicking on the div to make it disappear as well. So i'm trying to prevent that. How can I do that? And I still want the toggle affect on the button as well.

document.addEventListener('DOMContentLoaded', function() {

  var bx = document.getElementsByTagName('button')[0];
  bx.addEventListener('click', fx);

  function fx() {
    document.getElementById("myDropdown").classList.toggle("show");
  }

  window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {

      var dropdowns = document.getElementsByClassName("dropdown-content");
      var i;
      for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
        }
      }
    }
  }
});
.dropdown-content {
  display: none;
}

.show {
  display: block;
}
<button class="dropbtn">Dropdown</button>

<div id="myDropdown" class="dropdown-content">
  <h1>hello</h1>
  <img src='http://full.creative.touchtalent.com/The-enchanted-forest-97329.jpg'>
</div>

1 个答案:

答案 0 :(得分:1)

您的window.onclick处理程序仅检查您是否单击了按钮,而不是<div>内部。在您的情况中加入<div>支票:

if (!event.target.matches('.dropbtn') && !event.target.closest('.dropdown-content')) {
如果元素不匹配,则

Element.closest返回null,并且不是与其参数匹配的元素的后代。

相关问题