.toggleClass()
원문 링크
http://api.jquery.com/toggleClass/
함수들
개요 : 조건에 일치하는 요소들에 클래스를 추가하거나 삭제합니다. 인자를 스위치 하면서 클래스를 바꿀 수 있습니다.
- .toggleClass( className )
- className 토글을 위한 공백으로 연결된 하나 이상의 클래스 이름
- .toggleClass( className, switch )
- className 토글을 위한 공백으로 연결된 하나 이상의 클래스 이름
- switch 클래스의 추가 또는 제거를 결정하는 부울값
- .toggleClass( [switch] )
- switch 클래스의 추가 또는 제거를 결정하는 부울값
- .toggleClass( function(index, class, switch) [, switch] )
- function(index, class, switch) 토글하기 위한 클래스 명을 반환하는 함수. 인자로 요소집합의 인덱스와 기존 클래스 값, 그리고 클래스의 추가/제거를 결정하는 부울값으로 구성됩니다.
- switch 클래스의 추가 또는 제거를 결정하는 부울값
이 함수는 하나 이상의 클래스 명을 인자로 가집니다. 만약 클래스가 요소에 존재한다면 그 클래스를 제거하고 그 반대면 추가하게 됩니다. 간단한 예를 보시면 더 명확해 지실 겁니다.
<div class="tumble">Some text.</div>
스크립트를 $('div.tumble').toggleClass('bounce') 라고 하면 아래와 같은 결과가 됩니다.
<div class="tumble bounce">Some text.</div>
다시 한번 더 같은 $('div.tumble').toggleClass('bounce') 스크립트를 실행하면 <div> 에 tumble 클래스명만 남게됩니다.
<div class="tumble">Some text.</div>
.toggleClass('bounce spin')의 스크립트를 적용하면 <div class="tumble bounce spin"> 와 <div class="tumble">를 반복하게 됩니다.
.toggleClass()에 두번째 인자를 사용하면 클래스를 추가하거나 제거하는 것을 결정할 수 있습니다. 만약 이 인자를 true로 하면 추가하고 false로 하면 제거하게 되는 것입니다.
$('#foo').toggleClass(className, addOrRemove);를 풀어쓰면
if (addOrRemove) {
$('#foo').addClass(className);
}
else {
$('#foo').removeClass(className);
}
jQuery 1.4에 와서, 함수에 인자를 넘기지 않으면 모든 클래스를 토글하게 되었습니다. 또한 jQuery 1.4에서부터 인자로 함수를 사용할 수 있게 되었습니다.
$('div.foo').toggleClass(function() {
if ($(this).parent().is('.bar')) {
return 'happy';
} else {
return 'sad';
}
});이 예제는 <div class="foo">처럼 부모 요소의 클래스 중 bar가 포함되어 있다면 happy 토글이 되고 그렇지 않다면 sad 클래스를 토글하게 되는 것입니다.
예 제
문단(p)를 클릭하면 'highlight' 클래스를 토글합니다.
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { color:blue; }
.highlight { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.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>미리보기
클릭하면 노란색 배경색이 나왔다 없어졌다. ㅎㅎ
예 제
클릭한 수를 체크해주고 3의 배수만큼 클릭하면 "highlight" 클래스를 적용합니다.
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { color:blue; }
.highlight { background:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.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>
미리보기
예 제
버튼 마다 클래스를 토글할 수 있게 합니다.
<!DOCTYPE html>
<html>
<head>
<style>
.wrap > div { float: left; width: 100px; margin: 1em 1em 0 0;
padding=left: 3px; border: 1px solid #abc; }
div.a { background-color: aqua; }
div.b { background-color: burlywood; }
div.c { background-color: cornsilk; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div class="buttons">
<button>toggle</button>
<button class="a">toggle a</button>
<button class="a b">toggle a b</button>
<button class="a b c">toggle a b c</button>
<a href="#">reset</a>
</div>
<div class="wrap">
<div></div>
<div class="b"></div>
<div class="a b"></div>
<div class="a c"></div>
</div>
<script>
var cls = ['', 'a', 'a b', 'a b c'];
var divs = $('div.wrap').children();
var appendClass = function() {
divs.append(function() {
return '<div>' + (this.className || 'none') + '</div>';
});
};
appendClass();
$('button').bind('click', function() {
var tc = this.className || undefined;
divs.toggleClass(tc);
appendClass();
});
$('a').bind('click', function(event) {
event.preventDefault();
divs.empty().each(function(i) {
this.className = cls[i];
});
appendClass();
});
</script>
</body>
</html>
미리보기
복잡해 보이지만 별거는 아닙니다. 클래스를 각 버튼마다 토글할 수 있게 구성했네요. reset을 누르면 초기화 됩니다.
그럼 즐프하세요.
※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.
'프로그래밍 > jQuery' 카테고리의 다른 글
| jQuery API 정복 - 요소 별로 감싸기, wrapAll() (0) | 2011.11.22 |
|---|---|
| jQuery API 정복 - 넓이 구하기, width() (0) | 2011.11.22 |
| jQuery API 정복 - 요소 감싸기, wrap() (0) | 2011.11.22 |
| jQuery API 정복 - 감싼 요소 제거하기, unwrap() (0) | 2011.11.22 |
| jQuery API 정복 - 텍스트만 알아내기, text() (5) | 2011.11.22 |
| jQuery API 정복 - 수직 스크롤 이동, scrollTop() (2) | 2011.11.22 |
| jQuery API 정복 - 수평 스크롤 이동, scrollLeft() (0) | 2011.11.22 |
| jQuery API 정복 - 요소 바꾸기, replaceWith() (0) | 2011.11.22 |