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 Pop-up Event Monitor:
Copy Code code as follows:
$ ("#btn"). Bind ("click", Function (e) {
if (e.stoppropagation) {//need to block bubbling
E.stoppropagation ();
}else{
E.cancelbubble = true;
}
})
Copy Code code as follows:
$ (document). Bind ("click", Function (e) {
If (click event is not on model) {
Hidden modal box;
}
})
At first glance, this is no problem, but, in fact, there are many problems, first of all, we must pay attention to prevent bubbling, otherwise, click on the button, actually triggered the above two events, modal is not bouncing out, is actually bouncing out, and immediately hidden, and, when we have many small controls on the modal box, We can hardly judge the clicks in the Modal box.
Here, I think there is one of the most classic methods, very simple, but very ingenious,
First, the modal box listens for an event as follows:
Copy Code code as follows:
$ ("#modal"). Bind ("click", Function (event) {
if (event && event.stoppropagation) {
Event.stoppropagation ();
} else {
Event.cancelbubble = true;
}
});
Simply blocks the click event Bubbling in the Modal box,
And then:
Copy Code code as follows:
$ (document). One ("click", Function (e) {
var $target = $ (e.currenttarget);
if ($target. attr ("id")!= "modal") {
$ ("#modal"). CSS ("display", "none");
}
});
It's easy.