简体   繁体   English

菜单和父项上的活动类

[英]active class on menu and parent item

i have this HTML code for my menu:我的菜单有这个 HTML 代码:

<nav id="main-navigation" class="navigation-simple">
<ul>
    <li><a href="/">Home</a></li>           
    <li><a class="active-nav" href="">About Us</a>
    <ul>                        
        <li><a class="active-nav" href="about">About</a></li>               
        <li><a href="testimonials">Testimonials</a></li>
        <li><a href="meet-the-team">Meet The Team</a></li>  
    </ul>
    </li>
</nav>

i have added in the active-nav class but how can i automatically set the active class on parent and child items when the current URL is the href value of the link?我已经添加了active-nav类,但是当当前 URL 是链接的href值时,如何在父项和子项上自动设置活动类?

you need java script for this, jQuery is great for beginners!为此,您需要 Java 脚本,jQuery 非常适合初学者!

It could be done like this:可以这样做:

var url = window.location.href;
$( "nav li a" ).each(function(index) { 
  if (url.indexOf($(this).attr('href')) >= 0){ 
    $(this).addClass('active-nav');
  }
});

line by line -逐行 -

  1. get the current page url获取当前页面 url
  2. for each link in the navigation...对于导航中的每个链接...
  3. check if its href is in the current url检查它的 href 是否在当前 url 中
  4. if it is, add the class 'active-nav'如果是,请添加“active-nav”类
  5. close if statement关闭 if 语句
  6. close for loop关闭 for 循环

Something like:就像是:

$(function() {
  $('#main-navigation a').each(function() {
    if(this.href.indexOf(window.location.pathname) === 0) {
      $(this).addClass('active-nav');
    } else {
      // case when something was set to active by the server
      $(this).removeClass('active-nav');
    }
  });
});

will do the job.会做的工作。

Make sure you make the if condition safe to your sites deeplinking implementation (eg GET params, anchors or multiple domains with same pathname are possible within your navigation).确保 if 条件对您的站点深层链接实现安全(例如,在导航中可以使用 GET 参数、锚点或具有相同路径名的多个域)。

You can use the .filter() method to find the appropriate link and add the required class:您可以使用.filter()方法找到适当的链接并添加所需的类:

$('#main-navigation li > a').removeClass('active-nav')
.filter(function() {
    return location.href.indexOf(this.href) > -1;
})
.addClass('active-nav') //add class to matched element(s)
//add class to parent(s) of matched, if any
.each(function() {
    $($(this).parents('a'), '#main-navigation').addClass('active-nav');
});

Also remember to close your first ul .还记得关闭你的第一个ul

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM