首页 > 解决方案 > show and hide content by clicking button or background

问题描述

I tried to make a content, that gets viewed if you click a button an hides if you click that button again but also hides if you click anywhere else on the side except the content itself.
Like on www.w3schools.com if you click on tutorials.
my attempt was this:

$(":not(#content)").click does not work. But even if, it would also get triggered all the times the content is not visible anyways. No good code.

$(document).ready(function() {
  $("button").click(function() {
    $("#content").toggle();

  });
  $(":not(#content)").click(function() {
    $("#content").hide();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">This is the Content</div>

<button>switch</button>

<div> This is somewhere else </div>

标签: javascripthtmljquery

解决方案


如果单击的元素不是按钮或包含在内容中,您可以向隐藏内容的文档添加单击事件侦听器。

$(document).ready(function() {
  $("button").click(function() {
    $("#content").toggle();
  });
  $(document).click(function(e) {
    if(!$(e.target).closest('button, #content').length){
      $('#content').hide();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" style="display: none;">This is the Content</div>
<button>switch</button>
<div> This is somewhere else </div>


推荐阅读