【当前页面标识】highlightPage
◇组件名称:
当前页面标识
◇功能描述:
在导航条中,为所选定的页面的导航标签加上特殊的样式,使其标示为高亮。
◇调用方法:
addLoadEvent(highlightPage);
◇上下文情景:
为了突出当前的页面,使用JavaScript在当前页在对应的导航条上添加高亮。
◇工作方式&技术要点
·提取当前浏览器地址(通过window.location.herf),与导航条的锚点标签a的href属性的值进行比较,得出当前nav所在的页面。
·对所取得的元素设置here类,取得高亮效果。
·对body元素设置与页面相关的id,这样可以为每页创建特殊样式。
◇关键代码展示
·JavaScript代码
function highlightPage() {
if (!document.getElementsByTagName) return false;
if (!document.getElementById) return false;
if (!document.getElementById("navigation")) return false;
var nav = document.getElementById("navigation");
var links = nav.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
var linkurl = links[i].getAttribute("href");
var currenturl = window.location.href;
if (currenturl.indexOf(linkurl) != -1) {
links[i].className = "here";
var linktext = links[i].lastChild.nodeValue.toLowerCase();
document.body.setAttribute("id",linktext);
}
}
}
·HTML代码
1 <ul id="navigation">
2 <li><a href="home.html">Home</a></li>
3 <li><a href="contact.html">Contact</a></li>
4 </ul>
·CSS代码
1 #navigation a.here:link,
2 #navigation a.here:visited,
3 #navigation a.here:hover,
4 #navigation a.here:active {
5 color:#eff;
6 background-color:#799;
7 }
◇DEMO演示
浙公网安备 33010602011771号