Many times, when we do the front end, we will have such a small feature. Click to pop up a certain frame. However, sometimes we do n’t want to operate, we want to click on a blank space to hide the box. Assuming the following scene, a small button, click to pop up a modular box.
It's that simple, but when we want to click on the blank part, hide the modal box, add the button ID: BTN, the modal box ID: model
Maybe our simplest idea is to listen to an event directly on the Document. The pseudo code is as follows:
The button click the pop -up event to monitor:
Copy code code as follows:
$ ("#btn"). Bind ("click", function (e) {
if (E.Stoppropagation) {// Need to stop bubbling
e.stoppropagation ();
} Else {
e.CancelBubble = TRUE;
}
})
Copy code code as follows:
$ (docume) .Bind ("click", function (e) {
If (the click event is not on the model) {
Hidden modal box;
}
})
At first glance, there is no problem, but there are actually many problems. First of all, we have to pay attention to preventing bubbling, otherwise, click the button, actually triggered the above two events. Here, it was hidden again, and when we still have many small controls on the modal frame, it is difficult to judge the click in the modal box.
Here, I think there is the most classic method, which is simple, but very clever,
First of all, the incident is as follows on the model of the modal frame:
Copy code code as follows:
$ ("#MODAL"). bind ("click", function (event) {
If (event && event.stoppropagation) {{
event.stoppropagation ();
} Else {
event.cancelbubble = true;
}
});
Just simply prevent the clicks in the mode box bubbling,
Then:
Copy code code as follows:
$ (docume) .one ("click", function (e) {
var $ target = $ (e.currenttarget);
if ($ target.attr ("ID")! = "Modal") {{
$ ("#MODAL"). CSS ("Display", "None");
}
});
Do it, so easyy