简体   繁体   English

通过导航栏中的锚点链接显示/隐藏Div

[英]Show / Hide Divs via anchor links in a navbar

I have a navbar that uses anchor links to connect to different divs. 我有一个导航栏使用锚链接连接到不同的div。 I have all the div's hidden, but I want them to show based on what link you click. 我隐藏了所有div,但我希望它们根据您点击的链接显示。

<!-- 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. 我知道你可以使用jQuery做到这一点,但我无法做任何事情。 Right now the divs are set to display:none. 现在div设置为display:none。 'Home' should appear when you load the site. 加载网站时应显示“主页”。

One possible solution is to use the css pseudo-selector :target 一种可能的解决方案是使用css伪选择器: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/ CSS3选择器得到了很好的支持,但是:target可以提供奇怪或错误的行为,如下所述: http//css-tricks.com/on-target/

If you want to control it with jQuery... try it: http://jsfiddle.net/luiggi/kRgt6/ 如果你想用jQuery控制它...试试看: 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. 您可能需要在锚链接中添加某种CSS类,以便您可以更轻松地找到特定的触发器。

Just from memory, the code will be something like this (assuming anchors have the "ToggleDiv" class name). 仅从内存中,代码将是这样的(假设锚具有“ToggleDiv”类名)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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