简体   繁体   中英

Change menu background color for current page

I have a menu with a submenu
The html

<ul class="nav navbar-nav float-xs-right top-nav">
   <li class="nav-item"><a class="nav-link" href="/our-work/">Our Work</a></li>
   <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="/what-we-do/">What We Do</a>
          <div class="dropdown-menu">
              <a class="dropdown-item" href="/what-we-do/we-develop/">We Develop</a>
              <a class="dropdown-item" href="/what-we-do/we-promote/">We Promote</a>
              <a class="dropdown-item" href="/what-we-do/we-support/">We Support</a>
          </div>
    </li>
    <li class="nav-item"><a class="nav-link" href="/contact/">Contact</a></li>
</ul>

I am adding bg color using jQuery

function activeMenu() {
    var curr_url = window.location.pathname ;
    var curr_menu = $("a[href$='" + curr_url + "']");
    $(curr_menu).css("background", "#fff");
}
activeMenu();

It is changing bg color of a tag and if it is submenu than the submenu's bg color is changing.
But I want to change the bg color of the parent menu not the submenu.
Is there a possible solution to select the parent menu using jQuery?

See this jQuery method: https://api.jquery.com/parent/

In your case, I think this is what you're looking for;

function activeMenu() {
    var curr_url = window.location.pathname ;
    var curr_menu = $("a[href$='" + curr_url + "']");
    $(curr_menu).parent(".dropdown-toggle").css("background", "#fff");
}
activeMenu();

You can do this with vanilla javascript. Let's say your <ul> has an id of "menu":

const menu = document.getElementById("menu").children;
const list =  [...menu]
const currentPage = list.filter(li => li.children[0].pathname == window.location.pathname)
currentPage[0].className = "active"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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