๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

toggle ์€ ์‹ ์ด๋‹ค.

by ํ›„์•ผ- 2024. 1. 30.

๐Ÿ’ก ๊ธ‰ํ•˜๊ฒŒ ํ•˜์ง€ ๋ง๊ณ  ํ•˜๋‚˜์”ฉ ํ๋ฆ„์„ ํŒŒ์•…ํ•˜๊ธฐโ—โ—

๐Ÿ“– 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โ—