使用服务器端包含,选择当前导航元素的选项有哪些?
我使用10项无序列表作为导航栏。 使用SSI,我将标题和导航栏放入每个文件中。 我想要一种方法将class="active"
添加到当前活动页面的规则集(当前页面的相应
在每个页面中包含该文件意味着,在包含的文件中,没有项目可以具有活动类。
有几种代码可以做到这一点吗? (使用jQuery / JS)
我的另一个选择是将URL的最后部分与每个列表项中锚点的部分href
相匹配。
解决方案:(由RomanGorbatko提供)
var tab = window.location.pathname.split("/"); tab = tab[tab.length - 1]; // This probably is not efficient - suggestions? if (tab != "") $("#nav a#" + tab).addClass("active");
例如。 你有些页面:
你的菜单有下一个表格:
- index
- faq
- forum
现在,您检查页面的url。
var index = window.location.pathname.split('/')[1]; $('ul.li').removeClass('active'); $('li.' + index).addClass('active');
利润!
首先检测页面名称
var index = document.location.href.lastIndexOf("/") + 1; var page = document.location.href.substring(index,document.location.href.length);
考虑到导航栏在ul中有类导航栏,然后找到具有相同名称的li并添加活动类。
$('ul.navbar li').each(function() { $(this).removeClass('active'); if($.trim($(this).text()) == page) { $(this).addClass('active'); } });
这将满足您的要求。 注意:我假设li名称与页面名称相同
您可以先查看URL以检测页面名称,然后将页面名称与您在LI上定义的类相匹配。
if(document.location.href.indexOf('index')>-1) { $('li.index').addClass('active') }
如果您愿意,也可以使用页面标题而不是url来执行此操作。
另一个技巧是每页向BODY标签添加一个类,让CSS完成工作:
body.index li.index { background-color:#FF0000 } body.aboutus li.aboutus { .... whatever }
这是一个jquery / javascript免费解决方案的链接
我相信这会有所帮助。