如何隐藏页面的一部分,并显示另一部分时,单击标题?jQuery



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

一部分显示为none,另一部分显示。我想要完成的是,当其中一个h2元素被单击时,下面的部分将显示(除非它已经显示,那么它将保持显示),而另一个h2元素显示更改为none(除非它已经显示为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;
}

检查这个

可以使用jquery的show()hide()。有关更多信息,请参阅w3schools

文档见这里

    show () >
  • 隐藏()

JS

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

<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 ..请尝试一下。

使用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,以便在click事件中引用它们。

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

看到小提琴

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中添加多个section,这个jQuery就足够了:

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

欢迎在评论区提出任何问题

下面的jquery代码允许您隐藏显示div's,无论div's的数量,也不需要创建额外的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/

相关内容

最新更新