2012-11-09 42 views
0

我有一個導航列表:更改背景顏色用於修改DIV顯示/隱藏

<ul> 
<li><a href="#home">Home</a></li> 
<li><a href="#contact">Contact Me</a></li> 
</ul> 

當點擊主頁或聯繫,各自的DIV是隱藏或顯示。

<script> 

$("#tabs a").click(function(e){ 
    e.preventDefault(); 
    $(".toggle").hide(); 
    var toShow = $(this).attr('href'); 
    $(toShow).show(); 
}); 

</script> 

<div id="home" class="toggle" style="display:none"> This is the Home page.</div> 

問題

如何使這個詞在不同的導航列表中的背景顯示出其相應的div什麼時候?

E.g.當顯示div「home」時,導航欄中的「Home」一詞有藍色背景。

+0

使用CSS ...我沒有看到,你有問題。 – gdoron

+0

@gdoron - 那麼,我該怎麼做呢?谷歌什麼關鍵字? – Legendre

+0

沒關係,我回答了一個答案+一個DEMO,我希望它有幫助。先生,好日子。 – gdoron

回答

1

一個例子:

$('ul a').click(function() { 
    $(this).closest('ul').find('a').css('background-color', ''); 

    $(this).css('background-color', 'red') 
    return false; 
});​ 

A DEMO

+0

這是完美的!感謝和+1。 – Legendre

1

您需要將背景顏色添加到單擊的元素,但是您還需要確保將其從最後一次點擊的元素中移除。

$("#tabs a").click(function(e){ 
    e.preventDefault(); 
    $(".toggle").hide(); 
    var toShow = $(this).attr('href'); 
    // Remove the class from any siblings if it exists 
    $("#tabs a").removeClass('yourClass'); 
    // Add the class to the clicked #tab a 
    $(this).addClass('yourClass'); 
    $(toShow).show(); 
}); 

然後在屬性背景顏色和/或其他任何你想編輯你的CSS文件(例如,「yourClass」)創建一個類。

.yourClass { 
    background: #e2e2e2; 
} 
1
<script> 

    $("#tabs a").click(function(e){ 
     e.preventDefault(); 
     $(#tabs a).removeClass('yourClass'); 
     $(this).addClass('active'); 
     $(".toggle").hide(); 
     var toShow = $(this).attr('href'); 
     $(toShow).show(); 
    }); 

    </script> 

CSS

.active 
{ 
background-color:blue; 
} 

希望這有助於!

+0

這很好。問題:除此之外,點擊「與我聯繫」後,如何將「家庭」變成白色?這將永久性地將所有單詞變成藍色。我想我需要$(something).parent()css('background-color','white');.但是我用什麼來代替「某些東西」? – Legendre

+0

更新了代碼.. –

+0

感謝您的幫助。但是gdoron的答案似乎更簡潔明瞭。但+1爲你的努力。 – Legendre