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. There are many specific implementations below, when we do the front-end, we will have such a small function. 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, and add the button id: btn and the modal box id: model.
Perhaps our simplest idea is to listen directly to an event on the document. The pseudocode is as follows:
Click the button to bring up event listening:
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 the modal box;
}
})
At first glance, this is okay, but there are actually a lot of problems. First, we have to block bubbling. Otherwise, clicking the button actually triggers the above two events, modal cannot be displayed, but it is actually popped up and hidden immediately. Besides, when we have many widgets in the modal box, it is difficult to judge the clicks in the modal box.
Here, I think there is one of the most classic methods, which is simple but clever,
First, listen to an event for the modal box as follows:
The Code is as follows:
$ ("# Modal"). bind ("click", function (event ){
If (event & event. stopPropagation ){
Event. stopPropagation ();
} Else {
Event. cancelBubble = true;
}
});
Just to prevent 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