Click a box to pop up, but sometimes you don't want to operate it. You just want to click a blank space to hide the box. The following is a specific implementation:
Most of the time, we have such a small function when doing front-end operations. Click a box to pop up. However, if you don't want to operate it, you just want to click a blank space to hide the box. In the following scenario, click a small button to bring up a modal box. This is simple, but we want to hide the modal box when you click the blank part. Add the button id: btn and the modal box id: the simplest idea of model is to directly listen to an event on the document. The pseudocode is as follows: click the button to display the event listener: the code is as follows: $ ("# btn "). bind ("click", function (e) {if (e. stopPropagation) {// You Need To prevent bubbling e. stopPropagation ();} else {e. cancelBubble = true ;}}) the code is as follows: $ (document ). bind ("click", function (e) {if (click event not on model) {hide modal box;}) at first glance, this is okay,, in fact, there are many problems. First, we have to prevent bubbles. Otherwise, clicking the button actually triggers the above two events. modal cannot be played, but it actually pops up, it was immediately hidden, and when we had a lot When using the widget, it is difficult to determine the click in the modal box. Here, I think there is a classic method, which is simple but clever. First, listen to an event for the modal box as follows: $ ("# modal "). bind ("click", function (event) {if (event & event. stopPropagation) {event. stopPropagation ();} else {event. cancelBubble = true ;}}); simply prevents click events from bubbling in the modal box. Then, the Code is as follows: $ (document ). one ("click", function (e) {var $ target = $ (e. currentTarget); if ($ target. attr ("id ")! = "Modal") {$ ("# modal" ).css ("display", "none") ;}}); done, so easy