在外部单击时隐藏对话框

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在外部单击时隐藏对话框相关的知识,希望对你有一定的参考价值。

This is essentially how to detect an outside click for a dialog box on a website, using html/CSS/javascript/JQuery.

Essentially you need to understand event propagation how it works throughout the DOM with JQuery, to make this as simple as possible. Add a listener to the html or body element that detects a click, hide the box when it receives that event. Otherwise, stop the propagation of the event when the container receives it (the event).

If you have any question, or want a further explanation, don't hesitate to get in contact with me.

Cheers!
  1. <!DOCTYPE html>
  2. <html lang='en-us' xmlns='http://www.w3.org/1999/xhtml'>
  3. <head>
  4. <meta charset='utf-8'>
  5. <title>Page Title</title>
  6. <style type="text/css" media="screen">
  7. .button-container
  8. {
  9. width:300px;
  10. margin:0 auto;
  11. text-align: center;
  12. padding:0px 0px 25px 0px;
  13. }
  14. .form-container
  15. {
  16. display:none;
  17. width:300px;
  18. margin:0 auto;
  19. text-align: center;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="button-container">
  25. <button>Show Form</button>
  26. </div>
  27. <div class="form-container">
  28. <form action="event_prop_submit" method="get" accept-charset="utf-8">
  29. <fieldset id="" class="">
  30. <legend>Personal Information</legend>
  31. <label for="first_name">First Name</label><br/>
  32. <input type="text" name="first_name" value="" id="first_name" />
  33. <br/><br/>
  34. <label for="last_name">last_name</label><br/>
  35. <input type="text" name="last_name" value="" id="last_name">
  36. <br/><br/>
  37. </fieldset>
  38. <p><input type="submit" value="Continue &rarr;"></p>
  39. </form>
  40. </div>
  41. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  42. <script type="text/javascript">
  43. $(document).ready(function(){
  44. $('.form-container').click(function(event){
  45. console.log('click - form');
  46. //we want all click events in the form to stop at the form-container element, so that the event does not reach the body element
  47. event.stopPropagation();
  48. });
  49. $('html').click(function(event){
  50. console.log('click - body');
  51. //hide the form if the body is clicked
  52. $('.form-container').css('display','none');
  53. });
  54. $('button').click(function(event){
  55. $('.form-container').css('display','block');
  56. event.stopPropagation();
  57. });
  58. });
  59. </script>
  60. </body>
  61. </html>

以上是关于在外部单击时隐藏对话框的主要内容,如果未能解决你的问题,请参考以下文章

jQuery UI - 在外部单击时关闭对话框

在外部单击时 removeClass('active')

如何在按钮单击时切换下拉菜单并在外部单击时关闭?

防止在外部触摸时解除 BottomSheetDialogFragment

在外面按下时关闭对话框片段

如何在外部的任何点击上隐藏 div