jQueryのtoggleClassの例
単純な「p」タグの例を見てみましょう。
<p>This is paragraph</p>
-
$( ‘p’)。toggleClass( ‘highlight’)** を呼び出すと、ハイライトクラスが ‘p’タグに追加されます。
<p class="highlight">This is paragraph</p>
-
$( ‘p’)。toggleClass( ‘highlight’)** をもう一度呼び出すと、 ‘p’タグからハイライトクラスが削除されます。
<p>This is paragraph</p>
toggleClass()は次のjQueryコードと同等です。
if ($('p').is('.highlight')) {
$('p').removeClass('highlight');
}
else{
$('p').addClass('highlight');
}
jQueryのtoggleClassの例
<html>
<head>
<style type="text/css">
.highlight {
background:blue;
}
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<h1>jQuery toggleClass example</h1>
<p>This is paragraph1</p>
<p id="para2">This is paragraph2 (toggleClass effect)</p>
<p>This is paragraph3</p>
<p id="para4">This is paragraph4 (add/remove effect)</p>
<button id="toggleClass">toggle class</button>
<button id="addremoveClass">Add/Remove class</button>
<script type="text/javascript">
$("#toggleClass").click(function () {
$('#para2').toggleClass('highlight');
});
$("#addremoveClass").click(function () {
if ($('#para4').is('.highlight')) {
$('#para4').removeClass('highlight');
}
else{
$('#para4').addClass('highlight');
}
});
</script>
</body>
</html>