본문 바로가기
인간은 어떻게 배울까

[JS] 이벤트 리스너를 이용해서 속성을 껐다 켰다하기 (toggle)

by 개발하는 아인 2023. 6. 1.

 

<!DOCTYPE html>
<html>
<head>

  <meta charset="UTF-8">
  <title></title>
  
  <link rel="stylesheet" href="index.css">
  
</head>
<body>

  <ul>
      <li class="select one" id="one">
          <i class="check_icon"></i>
      </li>
      <li class="select two" id="two">
          <i class="check_icon"></i>
      </li>
      <li class="select three" id="three"> 
          <i class="check_icon"></i>
      </li>
  </ul>

  <script src="index.js"></script>

</body>
</html>
* {
    margin: 0;
    padding: 0;
}

ol, ul {
    list-style: none;
}

.select {
    width: 100%;
    height: 50px;
    margin-top: 10px;
    text-align: center;
}

.select.one {
    background-color: #b3b3b3;
}

.select.two {
    background-color: #56bec9;
}

.select.three {
    background-color: #7ef2f2;
}

.check_icon {
    display: none; /* 체크 박스가 보이지 않도록 설정 */
    width: 20px;
    height: 20px;
    background-color: yellow;
    margin-top: 15px;
}

.select.on .check_icon {
    display: inline-block; /* 체크 박스가 보이도록 설정 */
}
// javascript

// select 클래스를 가지고 있는 3개의 요소를 가져옵니다.
var selects = document.getElementsByClassName("select");


function handleOnclick() {
  // 선택된 요소에 on 클래스를 추가
  this.classList.toggle("on")
}

// 가져온 3개의 요소에 이벤트를 등록합니다.
for (var select of selects) {
    select.addEventListener("click", handleOnclick);
}