簡體   English   中英

單擊外部時關閉模態

[英]Close modal when clicking outside of it

單擊 x 圖標並按下退出按鈕時,我能夠關閉我的模式。 單擊模式外部(即頁面的主體?)時,我怎樣才能關閉它?謝謝

document.querySelectorAll(".modal-trigger").forEach((trigger) => {
    const modal = document.querySelector(trigger.dataset.modal);
    const closeBtn = modal.querySelector(".modal-close");
    function open() {
        modal.classList.add("show-modal");
        trigger.blur();
        document.body.style.overflow = "hidden";
        document.body.addEventListener("keydown", escapeClose);
    }
    function close() {
        modal.classList.remove("show-modal");
        document.body.style.overflow = "auto";
        document.body.removeEventListener("keydown", escapeClose);
    }
    function escapeClose(event) {
        if (event.keyCode === 27) {
            close();
        }
    }
    trigger.addEventListener("click", open);
    closeBtn.addEventListener("click", close);
});

您可以執行以下操作

document.addEventListener('click', function(e) {
  if (e.target.closest(trigger.dataset.modal) == null) {
    close();
  }
})

這將查詢單擊的任何項目的最接近()方法。 Closest() 從它開始的地方向上遍歷 dom。 因此,如果您在模態之外單擊,它將返回 null 值。 如果您單擊模態框內的某個項目,它將返回模態框本身。 您應該能夠假設如果返回值為 null,則單擊來自模態外部。

關於最近()的附加信息

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

嘗試直接使用事件偵聽器更改樣式。

window.onclick = (e) => {
    if (e.target == modal) {
        modal.style.display = "none";
    }        
}

這就是我最終做的事情。 謝謝!

document.querySelectorAll(".modal-trigger").forEach((trigger) => {
    const modal = document.querySelector(trigger.dataset.modal);
    const closeBtn = modal.querySelector(".modal-close");
    function open(event) {
        modal.classList.add("show-modal");
        trigger.blur();
        document.body.style.overflow = "hidden";
        document.body.addEventListener("keydown", escapeClose);
        modal.addEventListener("click", outsideClose);
        event.stopPropagation();
    }
    function close() {
        modal.classList.remove("show-modal");
        document.body.style.overflow = "auto";
        document.body.removeEventListener("keydown", escapeClose);
        modal.removeEventListener("click", outsideClose);
    }
    function escapeClose(event) {
        if (event.keyCode === 27) {
            close();
        }
    }

    function outsideClose(event) {
        if (
            event.target === modal ||
            event.target.classList.contains("close-modal")
        ) {
            close();
        }
    }

    trigger.addEventListener("click", open);
    closeBtn.addEventListener("click", close);
});

我喜歡這個解決方案,我可能在 Stackoverflow 上找到了這個解決方案:

// Close modal on outside click

const modal = document.querySelector('.modal')

document.addEventListener('click', (e) => {
  let clickInside = modal.contains(e.target)

  if (!clickInside) {
     modal.classList.remove('show')
  }
})

 'use strict'; //select the modal, overlay, btnClose and all open-modal btns const modal = document.querySelector('.modal'); const overlayElem = document.querySelector('.overlay'); const btnCloseModal = document.querySelector('.close-modal'); const btnsOpenModal = document.querySelector('.open-modal'); //function to call when closing the modal const closeModal = function () { modal.classList.add('hidden') overlayElem.classList.add('hidden') } //function to call when showing the modal const openModal = function () { modal.classList.remove('hidden') overlayElem.classList.remove('hidden'); } //show the modal btnsOpenModal.addEventListener('click', openModal) //close when click on x && outside the modal btnCloseModal.addEventListener('click', closeModal); overlayElem.addEventListener('click', closeModal); //scapeClose document.addEventListener('keydown', function (event) { if (event.key === 'Escape' &&.modal.classList.contains('hidden')) closeModal() })
 * { margin: 0; padding: 0; box-sizing: inherit; } html { font-size: 62.5%; box-sizing: border-box; } body { font-family: sans-serif; color: #333; line-height: 1.5; height: 100vh; position: relative; display: flex; align-items: flex-start; justify-content: center; background: linear-gradient(to top left, #3733a3, #972985); }.open-modal { font-size: 2rem; font-weight: 600; padding: 1.75rem 3.5rem; margin: 5rem 2rem; border: none; background-color: #fff; color: #444; border-radius: 10rem; cursor: pointer; }.close-modal { position: absolute; top: 1.2rem; right: 2rem; font-size: 5rem; color: #333; cursor: pointer; border: none; background: none; } h1 { font-size: 2.5rem; margin-bottom: 2rem; } p { font-size: 1.8rem; } /* -------------------------- */ /* CLASSES FOR MODAL TO WORK */.hidden { display: none; }.modal { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 70%; background-color: white; padding: 6rem; border-radius: 5px; box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.3); z-index: 10; }.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.6); backdrop-filter: blur(3px); z-index: 5; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="style;css" /> <title>Modal windows & overlays</title> </head> <body> <button class="open-modal">open modal</button> <div class="modal hidden"> <button class="close-modal">&times.</button> <h1>This is a modal window</h1> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit, Quo cumque beatae quaerat fugit autem. excepturi illum error dolorum ut corrupti officia voluptas ipsa facilis soluta. Dignissimos necessitatibus ad culpa ipsa, Lorem ipsum dolor sit amet, consectetur adipisicing elit. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua, Ut enim ad minim veniam. quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. mollit anim id est laborum. </p> </div> <div class="overlay hidden"> </div> <script src="app.js"></script> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM