2011-07-11 3 views
1

JQueryでこれを行う方法が不思議です。アイテムのcssは、すべてのメニューアイテムが共有するスプライトの一意の背景位置を選択するため、各アイテムのクラス名が一意である必要があるメニューがあります。したがって、アイテムをクリックすると、固有のアクティブな状態クラス名もトリガする必要があります。これを行う最善の方法は何ですか?jquery - 各クラス名がユニークなスプライトベースのナビゲーションのアクティブな状態を設定する

HTMLアンカーのクラス名がすでに'_active'で終わっていない場合はアンカーは、クリックされたクラス名に

<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

使用これはあなたのjqueryで

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

と、このようなCSSであなたの 'アクティブ' のルールを変更します。いずれかの代わりにアンダースコア

2

追加'_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/

注、これはアンカーが適用他のクラスを持っていないことを前提としています。

1

Ehhrrのドットを持つので

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

を、私は完全に間違った質問をするか、私の仲間のスタックオーバーフラワーはここで事を過度に複雑にする。

$('#menu').delegate('a', 'click', function() { 
    $(this).addClass('active').siblings().removeClass('active'); 
}); 
関連する問題