功能說明

  1. Hero Image
  2. modal開啟按鈕
  3. modal關閉按鈕


CSS重點

  • .modal-overlay中控制了modal的屬性,並利用visibility: hidden來隱藏modal :
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    ...
    .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(73, 166, 233, 0.5);
    display: grid;
    place-items: center;
    transition: var(--transition);
    visibility: hidden;
    z-index: -10;
    }
    ...
  • .open-modal卻將visibility屬性設為visible,讓其顯示 :
    1
    2
    3
    4
    5
    6
    ...
    .open-modal {
    visibility: visible;
    z-index: 10;
    }
    ...
  • 結論 :
    只要在HTML的modal標籤中加入open-modal的Class,就能顯示modal;反之,只要移除open-modal,就能隱藏modal

HTML重點

  1. Hero Image :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!-- 匯入背景圖片 -->
    <header class="hero">
    <!-- 白底方格 -->
    <div class="banner">
    <!-- 標題 -->
    <h1>modal project</h1>
    <!-- 開啟按鈕 -->
    <button class="btn modal-btn">
    open modal
    </button>
    </div>
    </header>

    將開啟按鈕的Class設為modal-btn

  2. modal視窗 :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!-- modal開啟後之背景 -->
    <div class="modal-overlay">
    <!-- modal開啟後之白底方格 -->
    <div class="modal-container">
    <!-- modal內容 -->
    <h3>model content</h3>
    <!-- 關閉按鈕 -->
    <button class="close-btn">
    <!-- 使用Font Awesome的Icon -->
    <i class="fas fa-times"></i>
    </button>
    </div>
    </div>

    將關閉按鈕的Class設為close-btn


JavaScript重點

  1. 利用class="modal-btn"去抓取開啟按鈕
    1
    const modalBtn = document.querySelector(".modal-btn"); 
  2. 利用class="close-btn"去抓取關閉按鈕
    1
    const closeBtn = document.querySelector(".close-btn");
  3. 利用class="sidebar"去抓取整個modal元素
    1
    const modal = document.querySelector(".modal-overlay");
  4. 將開啟按鈕新增點擊事件,進而顯示modal
    1
    2
    3
    modalBtn.addEventListener('click',function(){
    modal.classList.add("open-modal");
    });
  5. 將關閉按鈕新增點擊事件,進而隱藏modal
    1
    2
    3
    closeBtn.addEventListener('click',function(){
    modal.classList.remove("open-modal");
    });

參考與引用來源

  1. Hero Image介紹
  2. Modal簡介