๐ก ๊ธํ๊ฒ ํ์ง ๋ง๊ณ ํ๋์ฉ ํ๋ฆ์ ํ์ ํ๊ธฐโโ
๐ toggle
-> add(), remove(), replace(), toggle()
-> ์ค๋งํธํฐ ํค๊ณ ๋๊ธฐ
-> className ๋ฅผ ์ฌ์ฉ ์ํ๋ฉด ์๋ ์ฌ์ฉํ๊ณ ์๋ class ๊ฐ ์์ด์ง๊ฒ๋๋ค.
-> classList.contains , classList.remove , classList.add ๋ฅผ ์ฌ์ฉํด์ผ ํ๋๋ฐ ๋ ์ฌ์ด ๋ฐฉ๋ฒ์ด ์๋ค. ๊ทธ๊ฒ toggle์ด๋ค.
โ toggle ์ ์ฌ์ฉ์ํ์ ์
โพ html code (class big ์ถ๊ฐํ๊ธฐ)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ํ๋ฃจ ๊ณํํ</title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div class="title">
<h1 class="big">์๋
ํ์ธ์.</h1>
</div>
<script src="./js/index.js"></script>
</body>
</html>
โพ js code
const title = document.querySelector(".title h1");
function handleTitleClick() {
const clickedClass = "clicked";
if (title.classList.contains(clickedClass)) {
title.classList.remove(clickedClass);
} else {
title.classList.add(clickedClass);
}
}
title.addEventListener("click", handleTitleClick);
โพ css code
h1 {
color: blue;
/* ๋ณํ๋ ์๊ฐ ์กฐ์ ํ๊ธฐ */
transition: color 0.5s ease-in-out;
}
.clicked {
color: brown;
}
.big {
font-size: 50px;
}
โ toggle ์ ์ฌ์ฉํ์ ์
โพ js code
const title = document.querySelector(".title h1");
function handleTitleClick() {
title.classList.toggle("clicked");
}
title.addEventListener("click", handleTitleClick);
-> ํ ์ค๋ก ๊ตฌํ์ด ๊ฐ๋ฅํ๋ค. WoWโ