这个方法是之前在皮皮鲁实习的时候写的,当时BOSS交给我一任务:把导航的链接跟页面分类都对应的高亮起来。之前我还以为没有多少个页面,也就没有太再意, 大不了一个个的页面来呗。啊!!!!!页面那数量,一个个来会疯的!!!通过对链接的种类分析,我找到了点,哈哈。下面就是这个点的代码表示。最近也完善了一下, 比较好用,当时也测试了好久,才得出这么个玩意儿~欢迎交流:D
/** * 高亮显示当前链接元素[现在还得基于Jquery] * * * //HTML部分: ***link1*link2*link3*** //JS部分: * highLightCurrentLink('.navmenu ul li', 'active', -1); * * * @param string findDom 查找的当前元素 * @param string currentClass 当前选中的样式名 * @param string level相对于当前查到元素的层级关系,往下是-N, 往上是+N * * @return void */ var highLightCurrentLink = function(findDom, currentClass, level) { var modeFileExp = ''; var fileType = ''; var otherParam = null; var modeFlag = 0; var sameMode = {thread: "group"}; var otherMode = {my: "ac", tw: "ac", apps: "app", faq: "ct"}; var sameOtherParam = {my: {match: "ac=picture", param: "my.php?ac=profile"}}; var url = window.location.href; var nowHref = url.substring(url.lastIndexOf('/') + 1);//拿到当前访问的页面及查询内容 if(typeof nowHref == 'undefined' || nowHref == '') { return true; } if(nowHref.indexOf('?') > 0) { var nowPage = nowHref.substring(0, nowHref.indexOf('?')); //拿到当前的访问页面,不要.php } else { var nowPage = nowHref; } for(element in sameMode) { if(nowPage == element) { nowPage = sameMode[element]; break; } } //拿到其它的模式 for(var item in otherMode) { if(nowPage == item) { modeFlag = 1; var oMode = new RegExp(otherMode[item] + "=(\w+)" , "gi"); otherParam = nowHref.match(oMode); //拿到其它的决定变量 if(otherParam) { otherParam = otherParam[0]; var paramFlag = 0; for(var page in sameOtherParam) { if(nowPage == page && otherParam == sameOtherParam[page].match){ paramFlag = 1; otherParam = null; nowHref = sameOtherParam[page].param; } } } break; } } var maskLoc = nowHref.indexOf('?'); if(maskLoc != -1) { modeFileExp = nowHref.substring(nowHref.indexOf('.'), maskLoc); } else { modeFileExp = nowPage; } if(typeof level == 'undefined') { level = 0; } $(findDom).each(function() { var curHref = $(this).children('a').attr('href'); if(typeof curHref != 'undefined' && curHref != '') { if(curHref.match(modeFileExp) != null) { if(modeFlag == 1) { if(otherParam == null && curHref != nowHref) { return true; } else if(otherParam != null && curHref.match(otherParam) == null) { return true; } } var targetDom = $(this); if(level < 0) { for(var i = 0; i > level; i --) { targetDom = $(targetDom).children('a'); } } else if(level > 0) { for(var i = 0; i < level; i ++) { targetDom = $(targetDom).parent(); } } $(targetDom).addClass(currentClass); return false; } } }); }; //执行导航高亮查找并显示 jQuery(document).ready(function() { highLightCurrentLink('.menu ul li', 'active', -1); });
评论(2)
暂无评论!