如何隐藏页面的一个部分并在单击标题时显示其他部分? jQuery的

时间:2014-08-18 17:02:21

标签: javascript jquery html css

我在jsfiddle中创建了这个例子:http://jsfiddle.net/yt88bsnf/1/

一个部分的显示为none,另一个部分显示。我想要完成的是当点击一个h2元素时,显示下面的部分(除非它已经显示,然后它将保持显示),而另一个h2元素显示变为none(除非它已经有显示无。)

任何帮助或建议将不胜感激!感谢

HTML:

<div id="container">
    <h2>Section One</h2>
    <h2>Section Two</h2>
</div>

<div id="section_one">
    This is Section One
</div>

<div id="section_two">
    This is Section Two
</div>

CSS:

#container{
    overflow:hidden;
}

#container h2{
    float:left;
    margin-right:30px;
    cursor:pointer;
}

#section_two{
    display:none;
}

4 个答案:

答案 0 :(得分:1)

检查此fiddle

您可以使用jquery show()hide()。有关详细信息,请参阅W3Scools

对于文档,请参阅此处

<强> JS

$("#header1").click(function () {

    $("#section_one").show();
    $("#section_two").hide();
});
$("#header2").click(function () {

    $("#section_two").show();
    $("#section_one").hide();

});

<强> HTML

<div id="container">
     <h2 id="header1">Section One</h2>

     <h2 id="header2">Section Two</h2>

</div>
<div id="section_one">This is Section One</div>
<div id="section_two">This is Section Two</div>

我已经添加了每个h2一个id(header1和header2),并使用该ID分别显示和隐藏div ..请尝试一下..

答案 1 :(得分:0)

使用jQuery

可以使用

$(document).ready(function() {
    $('#button1').on('click', function() {
        $('#section_one').show();
        $('#section_two').hide();
    });

    $('#button2').on('click', function() {
        $('#section_one').hide();
        $('#section_two').show();
    });    
});

我在h2中添加了两个id,以便为点击事件引用它们。

如果您使用两个以上的部分,则可能需要使用循环来迭代它们并更改其可见性。在这种情况下,您还可以使用h2的索引来检查应显示哪个部分。

请参阅FIDDLE

答案 2 :(得分:0)

JS Fiddle Live Demo

一种简单的方法是将它们包装在各自的父母身上,如:

<div class="parent">
    <h1>Section One</h1>
    <p>Section One</p>
</div>

<div class="parent">
    <h1>Section Two</h1>
    <p style="visibility: hidden;">Section Two</p>
</div>

这样你可以在你的dom中添加多个部分,这个jQuery就足够了:

$(".parent").children("h1").click(function(){
    $(".parent").children("p").css("visibility", "hidden");
    $(this).siblings("p").css("visibility", "visible");
});

随意在评论中提出任何问题。

答案 3 :(得分:0)

以下jquery代码允许您隐藏显示div而不管div的数量,也不需要创建额外的id。

$("#container").on('click','h2',function(){//click on any h2 in container
     //hide all div's having section id starting with section_
   $("div[id^='section_']").hide();
    //show the div which has index position equal to the clicked h2 
  $($("div[id^='section_']")[$(this).index()]).show(); 
});

请参阅小提琴http://jsfiddle.net/3pmakwh4/