I'm making a one page website with sticky nav. What i want is when the select menu has been clicked the active link is highlighted with different color. this is my jquery script:
$(document).ready( function () {
var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
$("#main-menuid li a").removeClass("current");
$("#main-menuid li a[href='" + pathname + "']").addClass("current");
});
My navigation HTML:
<div id="main-menuid">
<ul>
<li class="homnav"><a href="#home">Home</a></li>
<li class="abonav"><a href="#about">About</a></li>
<li class="mennav"><a href="#menu">Menu</a></li>
<li class="connav"><a href="#contact">Contact</a></li>
</ul>
</div>
And 开发者_开发知识库my CSS for class .current:
.current {
color: #F05454;
}
Thanks a lot.
Since it’s hashes, you can probably just do the highlighting on click. Then just filter out the matching hash and add the class onload (anchors have the same properties as window.location):
var c = 'current';
$("ul a").click(function() {
$(this).addClass(c).parent().siblings().children('.'+c).removeClass(c);
}).filter(function() {
return this.hash == location.hash;
}).addClass(c);
http://jsfiddle.net/KL7QZ/
You have to use window.location.hash to get the #parameter
Try with the following code.
var pathname = window.location.hash;
$("#main-menuid li a").removeClass("current");
$("#main-menuid li a[href='" + pathname + "']").addClass("current");
jQuery("#main-menuid a").click(function(){
$("#main-menuid li a").removeClass("current");
$(this).addClass("current");
})
});
精彩评论