简体   繁体   中英

Show / Hide Divs via anchor links in a navbar

I have a navbar that uses anchor links to connect to different divs. I have all the div's hidden, but I want them to show based on what link you click.

<!-- NAV CONTAINER -->
<div class="navContainer">  
  <nav class="clearfix">
  <ul class="clearfix">
     <li><a href="#home">Home</a></li>
     <li><a href="#page1">Overview</a></li>
  </ul>
  </nav>
</div>

<!-- DIV CONTAINER -->
<div class="container">

<div class="sections" id="home">
homepage with title here 
</div>

<div class="sections" id="page1">
page 1
</div>
</div>

I know you can do it using jQuery but I haven't been able to make anything work. Right now the divs are set to display:none. 'Home' should appear when you load the site.

One possible solution is to use the css pseudo-selector :target

.sections {display:none;}
.sections:target {display:block;}

Demo

CSS3 selectors are pretty well supported but :target can give odd or buggy behaviour as mentioned here: http://css-tricks.com/on-target/

If you want to control it with jQuery... try it: http://jsfiddle.net/luiggi/kRgt6/

$(document).ready(function () {
    $("li.home").click(function () {
        $("#home").toggle();
        $("#page1").hide();
    });

    $("li.overview").click(function () {
        $("#page1").toggle();
        $("#home").hide();
    });
});

You'll likely need to add some sort of CSS class to the anchor links so you can find the specific triggers more easily.

Just from memory, the code will be something like this (assuming anchors have the "ToggleDiv" class name).

$('.ToggleDiv').each(function(el){
     var divId = $(el).attr("href");
     $(el).click(function(){
         $(divId).Toggle();
     });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM