Skills/JavaScript

221205 dom_08.html (상세설명 버튼 토글)

개발자 윤구나 2022. 12. 5. 12:33
<!DOCTYPE html>
<html lang="ko">
  <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>DOM_event</title>
    <script>
      document.addEventListener("DOMContentLoaded", () => {
        // 방법1.
        /*
        const btn = document.querySelector('.btn')
        const detailBox = document.querySelector('.detail')
        let isState = false

        btn.addEventListener('click', () => {
          if(!isState) {
            btn.innerHTML = '상세 설명 닫기'
            detailBox.style.display = 'block'
            isState = true
          } else {
            btn.innerHTML = '상세 설명 보기'
            detailBox.style.display = 'none'
            isState = false
          }
        })
        */

        // 방법2.
        let isOpen = false;
        let btn = document.querySelector(".btn");

        btn.addEventListener("click", function () {
          if (isOpen == false) {
            this.innerText = "상세 설명 닫기";
            document.querySelector(".detail").style.display = "block";
            isOpen = true;
          } else {
            this.innerText = "상세 설명 보기";
            document.querySelector(".detail").style.display = "none";
            isOpen = false;
          }
        });
      });
    </script>
    <style>
      .detail {
        display: none;
      }
    </style>
  </head>
  <body>
    <button class="btn">상세 설명 보기</button>
    <hr />
    
    <div class="detail">
      <h3>상세 설명 정보</h3>
      <p>
        It is a long established fact that a reader will be distracted by the
        readable content of a page when looking at its layout. The point of
        using Lorem Ipsum is that it has a more-or-less normal distribution of
        letters, as opposed to using 'Content here, content here', making it
        look like readable English. Many desktop publishing packages and web
        page editors now use Lorem Ipsum as their default model text, and a
        search for 'lorem ipsum' will uncover many web sites still in their
        infancy. Various versions have evolved over the years, sometimes by
        accident, sometimes on purpose (injected humour and the like).
      </p>
    </div>
  </body>
</html>