<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>문제5</title>
<style>
*{
margin:0;
padding:0;
box-sizing:border-box;
}
.wrap{
width:500px;
margin:100px auto;
display:flex;
justify-content:space-between;
}
.box{
width:150px;
height:150px;
background-color:lightgray;
border-radius:10px;
cursor:pointer;
display:flex;
justify-content:center;
align-items:center;
font-size:40px;
transition:0.3s;
}
.active{
background-color:tomato;
color:white;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
<script>
const boxAll = document.querySelectorAll('.box');
for(let i = 0; i < boxAll.length; i++){
boxAll[i].addEventListener('click', () => {
// 기존 active 제거
for(let j = 0; j < boxAll.length; j++){
boxAll[j].classList.remove('active');
}
// 클릭한 박스 active 추가
boxAll[i].classList.add('active');
});
}
</script>
</body>
</html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>문제5</title>
<style>
*{
margin:0;
padding:0;
box-sizing:border-box;
}
.wrap{
width:500px;
margin:100px auto;
display:flex;
justify-content:space-between;
}
.box{
width:150px;
height:150px;
background-color:lightgray;
border-radius:10px;
cursor:pointer;
display:flex;
justify-content:center;
align-items:center;
font-size:40px;
transition:0.3s;
}
.active{
background-color:tomato;
color:white;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
<script>
const boxAll = document.querySelectorAll('.box');
for(let i = 0; i < boxAll.length; i++){
boxAll[i].addEventListener('click', () => {
// 기존 active 제거
for(let j = 0; j < boxAll.length; j++){
boxAll[j].classList.remove('active');
}
// 클릭한 박스 active 추가
boxAll[i].classList.add('active');
});
}
</script>
</body>
</html>
#문제 5 : querySelectorAll + for문 + active