我在尝试将类设置为活动导航项时遇到问题。 我需要一些帮助来弄清楚我哪里出错了。 这是一些工作,但不正确,它默认为菜单项有一个子菜单,我无法看到我出错的地方。
当点击说“联系我们”时 - href将我带到联系页面但活动类不适用并保留在“产品”
我想要发生的是活动类适用于被点击而不会停留在“产品”上的项目
这是JSFiddle https://jsfiddle.net/2yv92roL/
提前感谢您的帮助!
这是HTML:
<nav class="navigation">
<ul class="mainmenu">
<li><a href="{{URL('/')}}">Home</a></li>
<li><a href="{{URL('ourphilosophy')}}">Our Philosophy</a></li>
<li><a href="">Products</a>
<ul class="submenu">
<li><a href="{{URL('/products')}}">Charbonnier Cookware</a></li>
<li><a href="{{URL('/dinnerware')}}">Charbonnier Dinnerware</a></li>
<li><a href="{{URL('/storageware')}}">Charbonnier Storageware</a></li>
</ul>
</li>
<li><a href="{{URL('/contact')}}">Contact us</a></li>
</ul>
</nav>
这是我的CSS:
/* define a fixed width for the entire menu */
.navigation {
width: 150px;
}
/* reset our lists to remove bullet points and padding */
.mainmenu, .submenu {
list-style: none;
padding: 0;
margin: 0;
}
/* make ALL links (main and submenu) have padding and background color */
.mainmenu a {
display: block;
text-decoration: none;
padding: 10px;
}
/* add hover behaviour */
.mainmenu a:hover {
background-color: #C5C5C5;
}
/* when hovering over a .mainmenu item,
display the submenu inside it.
we're changing the submenu's max-height from 0 to 200px;
*/
.mainmenu li:hover .submenu {
display: block;
max-height: 200px;
}
/*
we now overwrite the background-color for .submenu links only.
CSS reads down the page, so code at the bottom will overwrite the code at the top.
*/
/* hover behaviour for links inside .submenu */
.submenu a:hover {
background-color: #C5C5C5;
}
/* this is the initial state of all submenus.
we set it to max-height: 0, and hide the overflowed content.
*/
.submenu {
overflow: hidden;
max-height: 0;
-webkit-transition: all 0.5s ease-out;
}
.navigation ul li .active {
color: #0080A6;
}
这是我的JQuery
$(function() {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$(".navigation ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})
});
答案 0 :(得分:0)
您需要进行一些更改:
以下是更新后的代码:
$(function () {
var pgurl = "/" + window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$(".navigation ul li a").removeClass("active");
$(".navigation ul li a")
.each(function() {
if ($(this).attr("href") == pgurl)
$(this).addClass("active");
});
});