在外部单击时隐藏对话框
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!
<!DOCTYPE html> <html lang='en-us' xmlns='http://www.w3.org/1999/xhtml'> <head> <meta charset='utf-8'> <title>Page Title</title> <style type="text/css" media="screen"> .button-container { width:300px; margin:0 auto; text-align: center; padding:0px 0px 25px 0px; } .form-container { display:none; width:300px; margin:0 auto; text-align: center; } </style> </head> <body> <div class="button-container"> <button>Show Form</button> </div> <div class="form-container"> <form action="event_prop_submit" method="get" accept-charset="utf-8"> <fieldset id="" class=""> <legend>Personal Information</legend> <label for="first_name">First Name</label><br/> <input type="text" name="first_name" value="" id="first_name" /> <br/><br/> <label for="last_name">last_name</label><br/> <input type="text" name="last_name" value="" id="last_name"> <br/><br/> </fieldset> <p><input type="submit" value="Continue →"></p> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.form-container').click(function(event){ console.log('click - form'); //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 event.stopPropagation(); }); $('html').click(function(event){ console.log('click - body'); //hide the form if the body is clicked $('.form-container').css('display','none'); }); $('button').click(function(event){ $('.form-container').css('display','block'); event.stopPropagation(); }); }); </script> </body> </html>
以上是关于在外部单击时隐藏对话框的主要内容,如果未能解决你的问题,请参考以下文章