There is a bug in this article. After improvement, click somewhere else on the page to hide the displayed Div (improvement)
Background: today, a friend asked me "click a button to bring up a DIV, and then ask to click somewhere else on the page to hide this Div ".
First look at the effect:
Click me
- Chinese (simplified)
- English
Click "I" to hide the language list. You need to hide the DIV yourself.
The implementation is also very simple, but it should be noted that in the event displayed by clicking, You need to block event bubbling processing, otherwise the page Click Event will be triggered. However, this method also has a disadvantage: if an event in the same page also prevents bubbling, The DIV cannot be hidden. Therefore, special processing is required for such an event: hide the DIV yourself (but normally there are not many such events );
JS:
View code
$ (Document). Ready ( Function (){ // Click Event in the Language header to display the language list $ (". Language_selected"). Click ( Function (E) {$ ( ". Language_list" ). Toggle (); E. stoppropagation (); // Prevents event bubbling. Otherwise, the event will bubble to the following document click event. }); // Hide the language list when you click a document. $ (Document). Click ( Function () {$ ( ". Language_list" ). Hide ();}); // When you click a language item in the language list, the selected item is updated and the language list is hidden. $ (". Language_list li"). Click ( Function () {$ ( ". Language_selected"). Text ($ ( This ). Text (); $ ( ". Language_list" ). Hide () ;}); $ ( "# Nopopevent"). Click ( Function (E) {e. stoppropagation ();});});
CSS:
View code
. Language_selected{Cursor:Pointer;}. Language_list{Border:1px solid black;Display:None;}. Language_list Li{Cursor:Pointer;Border:1px solid red;}
HTML:
View code
< Div Style = "Width: 200px" > < Div Class = "Language_selected" > Chinese (simplified) </ Div > < Div Class = "Language_list" > < Ul > < Li > Chinese (simplified) </ Li > < Li > English </ Li > </ Ul > </ Div > </ Div > < Div ID = "Nopopevent" Style = "Width: 100px; Height: 100px; Border: 1px solid black ;" > Click "I". The language list is not hidden. You need to display the DIV yourself. </ Div >