我正在尝试为我的导航制作jQuery以突出显示活动菜单项(我的菜单是使用精灵btw制作的。)手动将class =“active”添加到其中一个菜单项,突出显示有效。但是使用我的jQuery代码,没有任何反应......
任何想法如何解决这个问题?
这是问题的演示小提琴。 http://jsfiddle.net/wvEBw/1/
HTML:
<nav>
<ul>
<li><a href="#" id="btn1"></a></li>
<li><a href="#" id="btn2" class="active"></a></li>
</ul>
</nav>
CSS :(动画精灵)
//...
/* sprite menu animations */
nav a#btn1 {
background-position:0px 0px;
width:82px;
}
nav a#btn1:hover {
background-position:0px -82px;
}
nav a#btn1.active {
background-position:0px -164px;
}
nav a#btn2 {
background-position:-108px 0px;
width:82px;
}
nav a#btn2:hover {
background-position:-108px -82px;
}
nav a#btn2.active {
background-position:-108px -164px;
outline: none;
}
jQuery的:
$("nav li").click(function() {
$("nav li a.active").removeClass("active"); //Remove any "active" class
$("a", this).addClass("active"); //Add "active" class to selected tab
$(activeTab).show(); //Fade in the active content
return false;
}
答案 0 :(得分:7)
你忘了在你的小提琴中添加jQuery库
并使用});
$("nav li").click(function ( e ) {
e.preventDefault();
$("nav li a.active").removeClass("active"); //Remove any "active" class
$("a", this).addClass("active"); //Add "active" class to selected tab
// $(activeTab).show(); //Fade in the active content
});
这篇文章也许有趣:Stop Misusing Return False
以下是DOCS的快速浏览:event.preventDefault
答案 1 :(得分:2)
您还可以根据当前网址突出显示导航href值的导航。这种方式在重定向和直接跳转到主页时更有效。考虑这个例子:
$(document).ready(function($) {
function markNavActive(){
var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
var listLinks = $('nav a');
listLinks.each(function() {
if ($(this).attr('href') == filename) {
// alert(filename);
$(this).addClass('active');
return;
}
if (filename == "") {
// alert(filename);
$('.nav a[href="index.php"]').addClass('active');
return;
}
});
}
markNavActive();
});