jQuery

[jQuery] 모달창 + CSS 애니메이션

helen2ye! 2022. 10. 3. 00:00
Modal paractice

로그인하세요

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modal paractice</title>
    <!-- BootStrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" 
        rel="stylesheet" 
        integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" 
        crossorigin="anonymous">
    <link href="main.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.1.min.js" 
            integity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" 
            crossorigin="anonymous">
    <style>
      .black-bg {
      width : 100%;
      height : 100%;
      position : fixed;
      background : rgba(124, 83, 83, 0.5);
      z-index : 5;
      padding: 30px;
      visibility: hidden;
      opacity: 0;
      transition: all 1s;
      }
      .white-bg {
          background: white;
          border-radius: 5px;
          padding: 30px;
      } 
      .show-modal{
          visibility: visible;
          opacity: 1;
      }
    </style>
    </script>
  </head>
  <body>
    <!-- 모달창은 보통 html 요소 가장 앞에 있기 때문에 body tag 상단에 기재 -->
    <div class="black-bg">
        <div class="white-bg">
          <h4>로그인하세요</h4>
          <button class="btn btn-danger" id="close">닫기</button>
        </div>
    </div> 
    
    <button id="login">로그인</button>

    <script>
        // 로그인 버튼 클릭하면, 모달창 띄우기(show-modal 클래스를 붙여주기)
        // document.getElementById('login').addEventListener('click',function(){});
        $('#login').on('click', function(){
            // document.querySelector('black-bg').classList.add('show-modal')
            $('.black-bg').addClass('show-modal');
            
            // $('.black-bg').fadeIn(); >> CSS로 처리해주는 것이 더 효율적
        })
        $('#close').on('click', function(){
            $('.black-bg').removeClass('show-modal');
        })
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js" 
            integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8" 
            crossorigin="anonymous">
    </script>
   </body>
</html>

모달창은 보통 페이지 맨 앞에(모든 html 요소 맨 앞에) 존재하므로, <body> tag 안에서 가장 상단에 적어주는 것이 좋음

css 에서 position: fixed; / z-index 등 참고

 

one-way UI 애니메이션(A상태에서 B상태로 이동하는 것)

  1. "시작스타일 / 최종스타일" 을 Class로 만들어놓기
  2. 원할 때 최종스타일로 변하라고 코드 짜기

CSS

  1. transition 동작에 소요되는 시간(1s 등) 설정
  2. display: none은 아예 삭제하는거고, visibility: hidden은 모습만 숨기는 것.
     애니메이션 적용할 때에는 visibility가 더 적합
  3. opacity : 0이면 투명 / 1이면 불투명

 

** 참고강의

https://codingapple.com/ JavaScript 입문과 웹 UI개발