[英]How to show/hide a section of content when a corresponding menu item is clicked, while hiding all other content?
[英]How to hide one section of the page and show the other section when a heading is clicked? jQuery
我在jsfiddle中制作了這個示例: http : //jsfiddle.net/yt88bsnf/1/
一個部分不顯示任何內容,而另一部分則顯示。 我要完成的工作是,單擊h2元素之一,則顯示以下部分(除非已顯示該部分,否則它將保持顯示狀態),而另一個h2元素顯示變為無(除非它已經具有無顯示)。
任何幫助或建議,將不勝感激! 謝謝
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()
。 有關更多信息,請參見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。請嘗試一下。
可以使用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的索引來檢查應顯示哪個部分。
一種簡單的方法是將它們包裝在各自的父母中,例如:
<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");
});
隨時在評論中提問。
下面的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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.