Recently, I am writing a front-end for the blog management background, which involves two requirements for highlighting the current menu on the same page. I remember that when I wrote a static page in that year, different styles were added to each page for highlighting. highlighted display I think it is quite common for the web Front-end. This is exactly what I want to use. I specially sorted out the two highlighted Categories I wrote.
The idea is simple. The first method is to traverse the href value of the link group and use indexOf to determine whether the href value is included in the current url value of the browser. this method has some limitations. For example, the menu in iframe cannot be determined like this. The second method is applicable to a wider range, and the Implementation idea is relatively simple, that is, by judging and clicking, load the highlighted style for the click item.
The first method is to determine the current URL value highlight code:
The Code is as follows:
// @ Mr. Think --- determine the URL to highlight the menu
Function highURL (menuId, classCur ){
If (! Document. getElementById) return false;
If (! Document. getElementById (menuId) return false;
If (! Document. getElementsByTagName) return false;
Var menuId = document. getElementById (menuId );
Var links = menuId. getElementsByTagName ("");
For (var I = 0; I Var menuLink = links [I]. href;
Var currentLink = window. location. href;
If (currentLink. indexOf (menuLink )! =-1 ){
Links [I]. className = classCur;
}
}
}
Parameter description:
1. menuId: the ID of the link group;
2. classCur: class Name of the style when highlighted.
Call method:
Window. onload = function highThis () {highURL ("youId", "youhighclass ");}
The second option is to highlight the current class after clicking:
The Code is as follows:
// @ Mr. Think --- click to highlight
Function highOnclick (elemId, classCur ){
If (! Document. getElementsByTagName) return false;
If (! Document. getElementById) return false;
If (! Document. getElementById (elemId) return false;
Var elemId = document. getElementById (elemId );
Var links = elemId. getElementsByTagName ("");
For (I = 0; I <links. length; I ++ ){
Links [I]. onclick = function (){
For (n = 0; n <links. length; n ++ ){
Links [n]. className = "";
This. className = classCur;
This. blur ();
}
}
}
}
Parameter description:
1. elemId: ID of the link group;
2. classCur: class Name of the style displayed after clicking.
Call method:
Window. onload = function highThis () {highOnclick ("youId", "youhighclass ");}
This method is highly scalable. For example, you can judge the parentNode. nodeName value to prevent a certain type of link from being traversed.
Source code download and demonstration
In view of some friends who do not know how to use it, I specially sorted out the pages related to this class I wrote earlier, and gave a DEMO page and a friend who needed it could view or download it.
Package