The starting point of writing the MenuSwitch class is that as there are more and more management items in the background, a scroll bar appears in the menu display department, causing the page to be unsightly. I wrote this JS class myself.
This function class adopts the popular web practice. It uses DIV + CSS + JS to separate styles and functions. Let me release the demo first.
Copy codeThe Code is as follows:
Function MenuSwitch (className ){
This. _ elements = [];
This. _ default =-1;
This. _ className = className;
This. _ previous = false;
}
MenuSwitch. prototype. setDefault = function (id ){
This. _ default = Number (id );
}
MenuSwitch. prototype. setPrevious = function (flag ){
This. _ previous = Boolean (flag );
}
MenuSwitch. prototype. collectElementbyClass = function (){
This. _ elements = [];
Var allelements = document. getElementsByTagName ("div ");
For (var I = 0; I <allelements. length; I ++ ){
Var mItem = allelements [I];
If (typeof mItem. className = "string" & mItem. className = this. _ className ){
Var h3s = mItem. getElementsByTagName ("h3 ");
Var uls = mItem. getElementsByTagName ("ul ");
If (h3s. length = 1 & uls. length = 1 ){
H3s [0]. style. cursor = "hand ";
If (this. _ default = this. _ elements. length ){
Uls [0]. style. display = "block ";
} Else {
Uls [0]. style. display = "none ";
}
This. _ elements [this. _ elements. length] = mItem;
}
}
}
}
MenuSwitch. prototype. open = function (mElement ){
Var uls = mElement. getElementsByTagName ("ul ");
Uls [0]. style. display = "block ";
}
MenuSwitch. prototype. close = function (mElement ){
Var uls = mElement. getElementsByTagName ("ul ");
Uls [0]. style. display = "none ";
}
MenuSwitch. prototype. isOpen = function (mElement ){
Var uls = mElement. getElementsByTagName ("ul ");
Return uls [0]. style. display = "block ";
}
MenuSwitch. prototype. toggledisplay = function (header ){
Var mItem;
If (window. addEventListener ){
MItem = header. parentNode;
} Else {
MItem = header. parentElement;
}
If (this. isOpen (mItem )){
This. close (mItem );
} Else {
This. open (mItem );
}
If (! This. _ previous ){
For (var I = 0; I <this. _ elements. length; I ++ ){
If (this. _ elements [I]! = MItem ){
Var uls = this. _ elements [I]. getElementsByTagName ("ul ");
Uls [0]. style. display = "none ";
}
}
}
}
MenuSwitch. prototype. init = function (){
Var instance = this;
This. collectElementbyClass ();
If (this. _ elements. length = 0 ){
Return;
}
For (var I = 0; I <this. _ elements. length; I ++ ){
Var h3s = this. _ elements [I]. getElementsByTagName ("h3 ");
If (window. addEventListener ){
H3s [0]. addEventListener ("click", function () {instance. toggledisplay (this) ;}, false );
} Else {
H3s [0]. onclick = function () {instance. toggledisplay (this );}
}
}
}
Package File Download