EverGiver
class 본문
728x90
클래스 활용
- addClass
- class를 추가할 때 사용 - removeClass
- class를 삭제할 때 사용 - toggleClass
- class를 추가 / 삭제 - hasClass
- class의 유무를 확인
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>class</title>
<style>
*{margin:0;padding:0;}
h1{
font-size:24px;
margin:20px;
}
.box{
width:100px;
height:100px;
line-height:100px;
margin:20px;
margin-bottom:50px;
background-color:#ddd;
border:3px solid #000;
text-align:center;
}
.on{
color:red;
background-color:gold;
}
.active{
background-color:#333;
border-color:gold;
color:#fff;
}
</style>
</head>
<body>
<h1>addClass : class를 추가할 때 사용</h1>
<div class="box box1">addClass</div>
<h1>removeClass : class를 삭제할 때 사용</h1>
<div class="box box2 active">removeClass</div>
<h1>toggleClass : class를 추가/삭제</h1>
<div class="box box3">toggleClass</div>
<h1>hasClass : class의 유무를 확인</h1>
<div class="box box4">hasClass</div>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(function(){
$('.box1') .click(function(){
$(this).addClass('active')
})
$('.box2').click(function(){
$(this).removeClass('active')
})
$('.box3').click(function(){
$(this).toggleClass('active')
})
$('.box4').click(function(){
$(this).toggleClass('active')
if($(this).hasClass('active') == true){
// box4에 active 0라고 표시
$(this).text('active O')
}else{
// box4에 active X라고 표시
$(this).text('active X')
}
})
})
</script>
</body>
</html>
728x90