我有一个带子菜单的菜单
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>
我使用jQuery添加bg颜色
function activeMenu() {
var curr_url = window.location.pathname ;
var curr_menu = $("a[href$='" + curr_url + "']");
$(curr_menu).css("background", "#fff");
}
activeMenu();
它正在改变标签的bg颜色,如果它是子菜单,则子菜单的颜色正在改变。
但是我想改变父菜单的bg颜色而不是子菜单。
是否有可能使用jQuery选择父菜单的解决方案?
答案 0 :(得分:3)
请参阅此jQuery方法:https://api.jquery.com/parent/
在你的情况下,我认为这正是你要找的;
function activeMenu() {
var curr_url = window.location.pathname ;
var curr_menu = $("a[href$='" + curr_url + "']");
$(curr_menu).parent(".dropdown-toggle").css("background", "#fff");
}
activeMenu();
答案 1 :(得分:1)
您可以使用香草javascript执行此操作。假设您的<ul>
的ID为“菜单”:
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"