jQuery API toggleClass 메서드

toggleClass() 메서드는 하나 이상의 클래스 이름을 매개변수로 사용합니다. 첫번째 버전에서는 일치하는 요소 안에 class 속성이 이미 존재할 때는 그 class 명을 지웠다. 반대로 인자로 주어진 클래스 속성이 없으면 추가된다.

1
<div class="tumble">Some text.</div>

toggleClass 적용시 $( “div.tumble” ).toggleClass( “bounce” )

1
2
//bounce가 추가되어있다.
<div class="tumble bounce">Some text.</div>

그 다음으로 아래 스크립트가 한번 더 실행되면 div 태그의 클래스는 원래대로 thumble만 남게된다.

$( “div.tumble” ).toggleClass( “bounce” )

1
<div class="tumble">Some text.</div>

동일한 div에 .toggleClass(“bounce spin”) 을 적용하면

1
<div class="tumble bounce spin"><div class="tumble"> 가 반복하게 된다.

toggleCalss 에 두번째 인수에는 true 나 false 값이 올 수있는데 인자로 넘어간 클래스가 해당 요소에 있을 경우 제거하고 없을 경우 추가 한다는 개념이다.

$( “#foo” ).toggleClass( className, addOrRemove );

아래와 동일한 코드 방식으로 작동한다.

1
2
3
4
5
if ( addOrRemove ) {
$( "#foo" ).addClass( className );
} else {
$( "#foo" ).removeClass( className );
}

jQuery 1.4 버전 부터는 toglleClass() 메서드에 아무 인자도 적지 않으면 모든 클래스 요소 이름이 토글된다. 또한 jQuery 1.4 버전 부터는 토글 된 클래스 이름은 함수를 통해서 전달할 수도 있다. 아래 예제

1
2
3
4
5
6
7
$( "div.foo" ).toggleClass(function() {
if ( $( this ).parent().is( ".bar" ) ) {
return "happy";
} else {
return "sad";
}
});

이 예제는 부모 요소에 bar 클래스가있는 경우 div class=”foo” 요소의 happy 클래스를 토글합니다. 그렇지 않으면 sad 클래스를 토글합니다.

예제

p 태그를 클릭할 때마다 highlight 클래스가 토글된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>toggleClass demo</title>
<style>
p {
margin: 4px;
font-size: 16px;
font-weight: bolder;
cursor: pointer;
}
.blue {
color: blue;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p class="blue">Click to toggle</p>
<p class="blue highlight">highlight</p>
<p class="blue">on these</p>
<p class="blue">paragraphs</p>

<script>
$( "p" ).click(function() {
$( this ).toggleClass( "highlight" );
});
</script>

</body>
</html>

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>toggleClass demo</title>
<style>
p {
margin: 4px;
font-size: 16px;
font-weight: bolder;
cursor: pointer;
}
.blue {
color: blue;
}
.highlight {
background: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p class="blue">Click to toggle (<span>clicks: 0</span>)</p>
<p class="blue highlight">highlight (<span>clicks: 0</span>)</p>
<p class="blue">on these (<span>clicks: 0</span>)</p>
<p class="blue">paragraphs (<span>clicks: 0</span>)</p>

<script>
var count = 0;
$( "p" ).each(function() {
var $thisParagraph = $( this );
var count = 0;
$thisParagraph.click(function() {
count++;
$thisParagraph.find( "span" ).text( "clicks: " + count );
$thisParagraph.toggleClass( "highlight", count % 3 === 0 );
});
});
</script>

</body>
</html>
Share