Click to pop a box, but sometimes do not want to operate, you want to click a space, hide the box, about this, there is a specific implementation of the following
Many times, we do the front end when there is such a small function, click to pop a box, but, sometimes do not want to operate, want to click on a blank, hide the box. Assuming the following scene, a small button, click Can pop a modal box. It's so simple, but we want to click on the blank part of the time to hide the modal box, add button id:btn, modal box id:model Perhaps our simplest idea is to listen to an event directly on the document, pseudocode as follows: button click on Pop-up event listener: code as follows: $ ("#btn"). Bind ("click", Function (e) { if (e.stoppropagation) {// Need to block bubbling e.stoppropagation (); }else{ e.cancelbubble = true; } }) code is as follows: $ (document). Bind ("click", Function (e) { if (click event not on model) { hidden modal box; } }) At first glance, there is no problem, but there are actually many problems, First, we have to be careful to stop bubbling, otherwise, click the button, actually triggered the above two events, modal is not bounce out, in fact, is bouncing out, and immediately hidden, and, when we have a lot of small controls on the modal box, we are very difficult to judge the click of modal frame. Here, I think there is a most classic method, very simple, but very ingenious, first, for the modal box to listen for an event like the following: code: $ ("#modal"). Bind ("click", function (Event) { if (event && event.stoppropagation) { event.stoppropagation (); } else { event.cancelbubble = true; } }); simply blocks the Click event in the Modal box to bubble, then: code as follows: $ ( Document. One ("click", Function (e) { var $target = $ (e.currenttarget); if ($target. attr ("id")!= "modal") { $ ("#m Odal "). CSS (" display "," none "); } }); fix, so easy