简体   繁体   English

通过单击打开 div 并通过单击外部关闭

[英]Open a div by clicking and close by clicking outside of it

A div is initially hidden, I want to display it when clicking a button.一个 div 最初是隐藏的,我想在单击按钮时显示它。 And once it is visible, I want to hide it when clicking anywhere outside that div.一旦它可见,我想在单击该 div之外的任何位置时隐藏它。

I'm trying following code, it displays the div, but the problem is in the second part (clicking outside) the box.我正在尝试以下代码,它显示 div,但问题出在框的第二部分(单击外部)。 The second part conflicts with first one so it hides it before displaying.第二部分与第一部分冲突,因此在显示之前将其隐藏。

How can I fix that?我该如何解决?

 $('button').on('click', function(e){ e.preventDefault(); $('.box').addClass('active'); }); //hide is by clicking outside.box $(document).on('click', function (e) { if ($('.box').is(':visible') &&.$('.box').is(e.target) &&.$('.box').has(e.target).length) { $(';box');hide(); } });
 button { margin-bottom: 20px; }.box { width: 200px; height: 120px; background: #fab1a0; display: none; }.active { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Click</button> <div class="box"></div>

You can stop the propagation of your event so that when button is clicked the event doesn't bubble up to the document .您可以停止event的传播,以便在单击按钮时事件不会冒泡到document Also instead of hide() , just using removeClass(...) should work for you.此外,而不是hide() ,只使用removeClass(...)应该适合你。

Also that event propagation doesn't stop in this button listener itself but from the next event listener which in your case is on the document and that is what we require.此外,事件传播不会在此按钮侦听器本身中停止,而是从下一个事件侦听器开始,在您的情况下,该事件侦听器在文档上,这就是我们所需要的。

 $('button').on('click', function(e){ e.stopPropagation(); $('.box').addClass('active'); }); //hide is by clicking outside.box $(document).on('click', function (e) { if ($('.box').is(':visible') &&.$('.box').is(e.target) &&.$('.box').has(e.target).length) { $(';box');removeClass('active'); } });
 button { margin-bottom: 20px; }.box { width: 200px; height: 120px; background: #fab1a0; display: none; }.active { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Click</button> <div class="box"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM