0

我正在使用导航栏,并且我希望在元素页面上的元素上有一个活动类。

例如,我需要 jQuery 来检查当前页面的 url,如果 url 是http://supjamess.tumblr.com/,它会将类添加activeaelement .indexhttp://supjamess.tumblr.com/ask并将类添加activeaelement .ask,依此类推。

如果有人可以提供代码,那将非常有帮助。

4

2 回答 2

2

我的示例需要 jQuery:

if ( window.location.pathname == '/' ) {
    var url_class = 'index';
} else {
    // Very first part of the path, so /path/to/url returns 'path'
    var url_class = window.location.pathname.split('/');
    url_class = url_class[1];
}

$('a.' + url_class).addClass('active');

这基本上是获取 URL 的路径名组件(在域之后和查询字符串之前,请参见此处),然后检查它是否为“/”,即索引并手动将 URL 类设置为“索引” .

否则,它会获取 URL 的第一个组件,因此/ask返回ask/questions/bar返回questions/users/edit/5返回users/tagged/layouts返回tagged等。

然后 jQuery 将该类添加active到具有给定类的任何元素中。

于 2012-07-06T01:08:40.023 回答
1

基于 location.pathname 的开关

 if (location.pathname == "/") {
      $("a.index").addClass("active");
 } else if (location.pathname == "ask") {
      $("a.ask").addClass("active");
 }
 ... and so on

额外的页面添加了额外的 else if 语句,因此代码变为:

 if (location.pathname == "/") {
      $("a.index").addClass("active");
 } else if (location.pathname == "/ask") {
      $("a.ask").addClass("active");
 } else if (location.pathname == "/tagged/layout") {
      $("a.layout").addClass("active");
 } else if (location.pathname == "/YOUR PATH") { // to add aditional pages, replace CAPS
      $("a.CLASS OF NAV LINK").addClass("active");
 }

您可以在 jsfiddle.net 或您自己的控制台(大多数浏览器中的 f12)中试用和试验 javascript

于 2012-07-06T01:10:28.980 回答