jQueryはコンテンツの表示と非表示を切り替えます
Demo:「表示」ボタンをクリックします.
1.折りたたみ可能なコンテンツ
折りたたみ可能なコンテンツのHTMLの例を以下に示します。
<section class="round-border">
<h2>Use jQuery toggle to hide/show collapse content</h2>
<div>
<button href="#collapse1" class="nav-toggle">Show</button>
</div>
<div id="collapse1" style="display:none">
<p>Bla bla bla bla</p>
</div>
</section>
上記の<div id = “collapse1” style = “display:none”>のdiv要素は隠れています。 ‘表示’ボタンをクリックしたときにコンテンツを表示するには、以下のように ‘表示’ボタンのクリックイベントを作成する必要があります。
$('.nav-toggle').click(function(){
//logic to show/hide collapsable content
});
2.セレクタを取得する
属性hrefから折りたたまれたコンテンツのセレクタを取得します。
var collapse__content__selector = $(this).attr('href');
3.表示と非表示に切り替えます
jQueryトグルを使用して、以下のような折りたたみ可能なコンテンツの表示/非表示を切り替えます。
var toggle__switch = $(this);
$(collapse__content__selector).toggle(function(){
if($(this).css('display')=='none'){
toggle__switch.html('Show');//change the button label to be 'Show'
}else{
toggle__switch.html('Hide');//change the button label to be 'Hide'
}
});
4.完全な例
<html>
<head>
<title>jQuery toggle to display and hide content</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.2.js"></script>
<script>
$(document).ready(function() {
$('.nav-toggle').click(function(){
//get collapse content selector
var collapse__content__selector = $(this).attr('href');
//make the collapse content to be shown or hide
var toggle__switch = $(this);
$(collapse__content__selector).toggle(function(){
if($(this).css('display')=='none'){
//change the button label to be 'Show'
toggle__switch.html('Show');
}else{
//change the button label to be 'Hide'
toggle__switch.html('Hide');
}
});
});
});
</script>
<style>
.round-border {
border: 1px solid #eee;
border: 1px solid rgba(0, 0, 0, 0.05);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
padding: 10px;
margin-bottom: 5px;
}
</style>
</head>
<body>
<section class="round-border">
<h2>jQuery toggle() to hide/show collapse content</h2>
<div>
<button href="#collapse1" class="nav-toggle">Show</button>
</div>
<div id="collapse1" style="display:none">
<p>Bla bla bla bla</p>
</div>
</section>
</body>
</html>
ソースコードをダウンロードする
それをダウンロードする –
jQuery-toggle-to-display-hide-content.zip
(1kb)