2011-07-11 32 views
1

我想知道如何用JQuery来做到这一点。我有一个菜单,其中每个项目的类名称都必须是唯一的,因为该项目的css会选择所有菜单项共享的精灵的唯一背景位置。所以当单击项目时,我需要触发一个唯一的活动状态类名称。什么是最好的方法来做到这一点?这里是我的代码:jquery - 设置菜单活动状态为基于精灵的导航,其中每个类名称是唯一的

HTML

<div id="menu"> 
    <a href="javascript:void(0);" class="trailer">Trailer</a> 
    <a href="javascript:void(0);" class="bios">Bios</a> 
    <a href="javascript:void(0);" class="photos">Photos</a> 
    <a href="javascript:void(0);" class="synopsis">Synopsis</a> 
    <a href="javascript:void(0);" class="news">News</a> 
</div> 

CSS

#menu a { background: url(../images/menu.png) no-repeat; height:16px; overflow:hidden; display:block; text-indent:-10000px; float:left; margin-left:63px;} 
#menu a:first-child { margin-left: 0;} 
#menu a.trailer { width: 91px;} 
#menu a.trailer:hover, #menu a.trailer_active { background-position: 0px -20px;} 
#menu a.bios { width: 50px; background-position: -153px 0;} 
#menu a.bios:hover, #menu a.bios_active { background-position: -153px -20px;} 
#menu a.photos { width:86px; background-position: -272px 0;} 
#menu a.photos:hover, #menu a.photos_active { background-position: -272px -20px;} 
#menu a.synopsis { width:103px; background-position: -423px 0;} 
#menu a.synopsis:hover, #menu a.synopsis_active { background-position: -423px -20px;} 
#menu a.news { width:62px; background-position: -579px 0;} 
#menu a.news:hover, #menu a.news_active { background-position: -579px -20px;} 
+0

你不想使用':active'? –

+0

我不明白这个问题。为什么不向点击(活动)锚点添加类名? – jAndy

回答

2

使用这样的:

#menu a.trailer:hover, #menu a.trailer.active { background-position: 0px -20px;} 

所以用一个点而不是下划线

2

追加'_active'类名时,锚被点击,如果锚的类名尚未与'_active'结束。

var re = /_active$/g; 

$('#menu').delegate('a[class]', 'click', function() 
{ 
    var $this = $(this), 
     className = this.className; 

    if (className.match(re)) return; 

    // remove _active from siblings 
    $this.siblings().attr('class', function (i, val) 
    { 
     return val.replace(re, ''); 
    }); 

    // add _active to self 
    this.className = className + '_active'; 
}); 

演示:http://jsfiddle.net/mattball/xppZu/

注意,这个假设锚将没有应用其他类。在您的jQuery

$('#menu>a').click(function() { 
    $(this).addClass('active') 
} 

,改变你的 '积极的' 规则在CSS中这样

1

Ehhrr,无论是我的问题完全错误,或者我的同伴stackoverflowers在这里过于复杂。

$('#menu').delegate('a', 'click', function() { 
    $(this).addClass('active').siblings().removeClass('active'); 
}); 
相关问题