在单个页面上创建多个模态

时间:2016-11-17 00:59:38

标签: javascript html modal-dialog

根据w3schools.com的示例代码,我在单个网页上创建多个模态时遇到了一些问题。我正在使用的代码就是这个:http://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal2

我在问题上找到了一个类似的主题但是在jsfiddle中尝试解决方案之后我仍然没有得到任何结果,是否有人有任何想法?

上一主题: Support for Multiple Modal Single Page

https://jsfiddle.net/oa1dr3q6/

<h2>1st Modal</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Modal Header</h2>
</div>
<div class="modal-body">
<p>Some text in the Modal Body</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>

<h2>2nd Modal</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Modal Header</h2>
</div>
<div class="modal-body">
<p>Some text in the Modal Body</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>

   

脚本:

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
    modal.style.display = "none";
}
}

8 个答案:

答案 0 :(得分:1)

为什么你使用这么多代码和javascript做一些你可以用CSS和HTML做的事情? (简化示例,当然可以添加动画等)

&#13;
&#13;
[id^=modal] {
  display: none;
  border: 1px solid red;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  min-height: 3em;
  min-width: 5em;
  max-width: 10em;
  }
input[type=checkbox] {
  position: absolute;
  clip: rect(0 0 0 0);
  }
#modal1:target {
  display: block;
  }
#modal2:target {
  display: block;
  }
[id^=modal] a {
  float: right;
  }
&#13;
<div id="content">
    <p>This is the content-container</p>
    <a href="#modal1">Open first modal</a><br>
    <a href="#modal2">Open second modal</a>
  <div id="modal1"><a href="#">Close</a>This is the first modal</div>
  <div id="modal2"><a href="#">Close</a>This is the second modal</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

更新2020年9月:我的回答中的代码与我的博客文章中的代码略有过时。请查看帖子本身以获取最新版本以及说明。

我知道我要在这里取消死掉的帖子,但是我想提出一个更清洁,更可维护的解决方案。我在博客上针对how to create multiple modals on a single page撰写了深入的指南。解释有些复杂,因此,如果您想了解这段代码的工作原理,请在那篇文章中详细介绍。

下面是两个版本的代码,具体取决于您要完成的工作:多个堆叠模式或多个并排模式。

我希望这对以后遇到此问题的人有所帮助。

创建堆叠模态

// Stack of modals
let currentlyOpenModals = [];

const noModalsOpen = () => !currentlyOpenModals.length;

const openModal = modalId => {
  const modalWrapper = document.getElementById(modalId);
  modalWrapper.classList.add("visible");
  currentlyOpenModals.push(modalWrapper);
};

// By definition, it's always the topmost modal that will be closed first
const closeTopmostModal = () => {
  if (noModalsOpen()) {
    return;
  }

  const modalWrapper = currentlyOpenModals[currentlyOpenModals.length - 1];
  modalWrapper.classList.remove("visible");
  currentlyOpenModals.pop();
};

const modalTriggers = document.querySelectorAll(".modal-trigger");
modalTriggers.forEach(modalTrigger => {
  modalTrigger.addEventListener("click", clickEvent => {
    const trigger = clickEvent.target;
    const modalId = trigger.getAttribute("data-modal-id");
    openModal(modalId);
  });
});

// Otherwise, clicking the content of a modal will propagate the click to the modal wrapper,
// and that will close the entire thing. That's not what we want!
document.querySelectorAll(".modal-window").forEach(modal => {
  modal.addEventListener("click", clickEvent => {
    clickEvent.stopPropagation();
  });
});

const modalWrappers = document.querySelectorAll(".modal-wrapper");
modalWrappers.forEach(modalWrapper => {
  modalWrapper.addEventListener("click", () => {
    closeTopmostModal();
  });
});

document.querySelectorAll(".close-modal-button").forEach(closeModalButton => {
  closeModalButton.addEventListener("click", () => {
    closeTopmostModal();
  });
});

document.body.addEventListener("keyup", keyEvent => {
  if (keyEvent.key === "Escape") {
    closeTopmostModal();
  }
});
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    align-items: center;
    display: flex;
    flex-direction: column;
    font-family: Arial;
    font-size: 18px;
    height: 100vh;
    justify-content: center;
}

p {
    margin-bottom: 1em;
}

.modal-wrapper {
    align-items: center;
    background-color: rgba(100, 100, 100, 0.5);
    bottom: 0;
    display: flex;
    flex-wrap: wrap;
    height: 100vh;
    justify-content: center;
    left: 0;
    opacity: 0;
    position: fixed;
    right: 0;
    transition: all 0.2s ease-in-out;
    visibility: hidden;
    width: 100%;
    z-index: 1000;
}

.modal-wrapper.visible {
    opacity: 1;
    visibility: visible;
}

.modal-window {
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
    padding: 20px;
    transform: scale(0);
    transition: 0.2s ease-in-out all;
}

.modal-wrapper.visible .modal-window {
    transform: scale(1);
}

.modal-header {
    align-items: center;
    border-bottom: 2px solid black;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    padding-bottom: 20px;
}

.close-modal-button {
    align-items: center;
    cursor: pointer;
    display: flex;
    height: 30px;
    justify-content: center;
    width: 30px;
}

.close-modal-button::before {
    content: "X";
    color: rgb(112, 112, 112);
}

.close-modal-button:hover::before {
    color: black;
}

.modal-trigger, a {
    color: rgb(10, 47, 255);
    cursor: pointer;
    text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>Stacked Modals Demo</title>
</head>
<body>
    <p>Lorem ipsum. <span class="modal-trigger" data-modal-id="modal1">Click this trigger</span> to open a modal.</p>
    <p>Close a modal by clicking off to the side, clicking the X, or pressing Escape.</p>
    <div class="modal-wrapper" id="modal1">
        <section class="modal-window">
            <header class="modal-header">
                <h3>Title goes here...</h3>
                <div class="close-modal-button"></div>
            </header>
            <p>Congrats, you've opened a modal!</p>
            <p>Now open <span class="modal-trigger" data-modal-id="modal2">another modal</span>!</p>
        </section>
    </div>
    <div class="modal-wrapper" id="modal2">
        <section class="modal-window">
            <header class="modal-header">
                <h3>Modalception ?</h3>
                <div class="close-modal-button"></div>
            </header>
            <p>Noice.</p>
        </section>
    </div>
    <script src="index.js"></script>
</body>
</html>

并排打开多个模式

请注意,由于容器上有flex-wrap: wrap,因此该解决方案可以完全响应。您可以在一个页面上打开任意数量的模态,它们会彼此流动。

但是请注意,您需要全屏查看此内容。

let currentlyOpenModals = {};
const noModalsOpen = () => !Object.keys(currentlyOpenModals).length;
const modalWrapper = document.querySelector(".modal-wrapper");

const openModal = modalId => {
  // If we're opening the first modal, make sure the wrapper becomes visible too
  if (noModalsOpen()) {
    modalWrapper.classList.add("visible");
  }

  const modal = document.getElementById(modalId);
  modal.classList.add("visible");
  currentlyOpenModals[modalId] = modal;
};

const closeModal = modalId => {
  if (noModalsOpen()) {
    return;
  }

  const modal = currentlyOpenModals[modalId];
  modal.classList.remove("visible");
  delete currentlyOpenModals[modalId];

  // If we closed the last open modal, hide the wrapper
  if (noModalsOpen()) {
    modalWrapper.classList.remove("visible");
  }
};

const closeAllModals = () => {
  // Iterate over the IDs in our map and close each modal with that ID
  Object.keys(currentlyOpenModals).forEach(closeModal);
};

const modalTriggers = document.querySelectorAll(".modal-trigger");
modalTriggers.forEach(modalTrigger => {
  modalTrigger.addEventListener("click", clickEvent => {
    const trigger = clickEvent.target;
    const modalId = trigger.getAttribute("data-modal-id");
    openModal(modalId);
  });
});

document.querySelectorAll(".modal-window").forEach(modal => {
  modal.addEventListener("click", clickEvent => {
    clickEvent.stopPropagation();
  });
});

modalWrapper.addEventListener("click", () => {
  closeAllModals();
});

document.querySelectorAll(".close-modal-button").forEach(closeModalButton => {
  closeModalButton.addEventListener("click", clickEvent => {
    const modalToClose = clickEvent.target.closest(".modal-window");
    closeModal(modalToClose.id);
  });
});

document.body.addEventListener("keyup", keyEvent => {
  if (keyEvent.key === "Escape") {
    closeAllModals();
  }
});
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-family: Arial;
    font-size: 18px;
}

p {
    margin-bottom: 1em;
}

.modal-wrapper {
    align-items: center;
    background-color: rgba(100, 100, 100, 0.5);
    bottom: 0;
    display: flex;
    flex-wrap: wrap;
    height: 100vh;
    justify-content: center;
    left: 0;
    opacity: 0;
    position: fixed;
    right: 0;
    transition: all 0.2s ease-in-out;
    visibility: hidden;
    width: 100%;
    z-index: 1000;
}

.modal-wrapper.visible {
    opacity: 1;
    visibility: visible;
}

.modal-window {
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
    padding: 20px;
    transform: scale(0);
    transition: 0.2s ease-in-out all;
    position: absolute;
    margin: 1em;
}

.modal-window.visible {
    transform: scale(1);
    position: relative;
}

.modal-header {
    align-items: center;
    border-bottom: 2px solid black;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    padding-bottom: 20px;
}

.close-modal-button {
    align-items: center;
    cursor: pointer;
    display: flex;
    height: 30px;
    justify-content: center;
    width: 30px;
}

.close-modal-button::before {
    content: "X";
    color: rgb(112, 112, 112);
}

.close-modal-button:hover::before {
    color: black;
}

.modal-trigger {
    color: rgb(10, 47, 255);
    cursor: pointer;
    text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>Side-by-Side Modals Demo</title>
</head>
<body>
    <p>Lorem ipsum. <span class="modal-trigger" data-modal-id="modal1">Click this trigger</span> to open a modal.</p>
    <p>Close a modal by clicking off to the side, clicking the X, or pressing Escape.</p>
    <div class="modal-wrapper">
        <section class="modal-window" id="modal1">
            <header class="modal-header">
                <h3>Title goes here...</h3>
                <div class="close-modal-button"></div>
            </header>
            <p>Congrats, you've opened a modal!</p>
            <p>Now open <span class="modal-trigger" data-modal-id="modal2">another modal</span>!</p>
        </section>
        <section class="modal-window" id="modal2">
            <header class="modal-header">
                <h3>Modalception ?</h3>
                <div class="close-modal-button"></div>
            </header>
            <p>Noice.</p>
        </section>
    </div>
    <script src="index.js"></script>
</body>
</html>

答案 2 :(得分:1)

我知道我迟到了。

看看这个。

 body {
            font-family: Arial, Helvetica, sans-serif;
        }

        /* The Modal (background) */
        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 80px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
            overflow: auto;
        }

        /* Modal Content */
        .modal-content {
            max-height: 80%;
            overflow: auto;
            position: relative;
            background-color: #fefefe;
            margin: auto;
            padding: 0;
            border: 1px solid #888;
            width: 80%;
            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
            -webkit-animation-name: animatetop;
            -webkit-animation-duration: 0.4s;
            animation-name: animatetop;
            animation-duration: 0.4s
        }

        /* Add Animation */
        @-webkit-keyframes animatetop {
            from {
                top: -300px;
                opacity: 0
            }

            to {
                top: 0;
                opacity: 1
            }
        }

        @keyframes animatetop {
            from {
                top: -300px;
                opacity: 0
            }

            to {
                top: 0;
                opacity: 1
            }
        }

        /* The Close Button */
        .close {
            color: white;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

        .modal-header {
            padding: 2px 16px;
            background-color: #5cb85c;
            color: white;
        }

        .modal-body {
            padding: 2px 16px;
        }

        .modal-footer {
            padding: 2px 16px;
            background-color: #5cb85c;
            color: white;
        }
<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="modal.css">
</head>

<body>
    <button id="myBtn">Button 1</button>
    <button id="myBtn1">Button 2</button>
    <button id="myBtn2">Button 3</button>

    <!-- The Modal -->
    <div id="myModal" class="modal">

        <!-- Modal content -->
        <div class="modal-content">
            <div class="modal-header">
                <span class="close">&times;</span>
                <h2>Button 1 Clicked</h2>
            </div>
            <div class="modal-body">
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus aspernatur perferendis ad sunt.
                    Eius, possimus? Quae at eum repudiandae obcaecati vitae accusantium, perferendis sapiente
                    temporibus, necessitatibus voluptatem iste cumque et?</p>
            </div>
            <div class="modal-footer">
                <h3>Modal Footer</h3>
            </div>
        </div>

    </div>

    <!-- The Modal -->
    <div id="myModal1" class="modal">

        <!-- Modal content -->
        <div class="modal-content">
            <div class="modal-header">
                <span class="close">&times;</span>
                <h2>Button 2 Clicked</h2>
            </div>
            <div class="modal-body">
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores voluptatum ipsa cum aliquid, ex
                    inventore, culpa obcaecati modi deleniti enim consequuntur tenetur. Earum numquam sit ratione eum
                    sequi praesentium, unde maxime ullam iure rem mollitia perferendis eos possimus neque, nisi dicta.
                    Obcaecati dignissimos, dolores labore rerum quisquam non explicabo repellat!</p>
            </div>
            <div class="modal-footer">
                <h3>Modal Footer</h3>
            </div>
        </div>

    </div>

    <!-- The Modal -->
    <div id="myModal2" class="modal">

        <!-- Modal content -->
        <div class="modal-content">
            <div class="modal-header">
                <span class="close">&times;</span>
                <h2>Button 3 Clicked</h2>
            </div>
            <div class="modal-body">
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Reprehenderit laudantium quia non laborum
                    ea, similique ex iusto minus obcaecati optio sapiente aut eveniet porro odio veniam excepturi
                    facilis iste fuga? Porro atque odio, fuga blanditiis voluptate ducimus veritatis id ea possimus?
                    Facilis tempore officiis quos assumenda dolorem placeat sed veniam dolor eveniet magnam. Iure ullam
                    odit qui, magni suscipit pariatur nesciunt temporibus aspernatur doloribus quis nobis quas esse
                    perspiciatis, asperiores eum quidem placeat minus alias veniam molestias sit. Ipsam numquam,
                    sapiente facere voluptatem eum, maiores blanditiis cupiditate corporis quos ratione, quia
                    praesentium dolore nihil voluptatum impedit quae consequatur sit pariatur.
                </p>
            </div>
            <div class="modal-footer">
                <h3>Modal Footer</h3>
            </div>
        </div>

    </div>

    <script>
        var datamap = new Map([
            [document.getElementById("myBtn"), document.getElementById("myModal")],
            [document.getElementById("myBtn1"), document.getElementById("myModal1")],
            [document.getElementById("myBtn2"), document.getElementById("myModal2")]
        ]);

        datamap.forEach((value, key) => {
            doModal(key, value);
        });

        function doModal(anchor, popupbox) {

            // Get the <span> element that closes the modal
            var span = popupbox.getElementsByClassName("close")[0];

            anchor.addEventListener("click", function (event) {
                popupbox.style.display = "block";
            });

            span.addEventListener("click", function (event) {
                popupbox.style.display = "none";
            });

            window.addEventListener("click", function (event) {
                if (event.target == popupbox) {
                    popupbox.style.display = "none";
                }
            });
        }
    </script>

</body>

</html>

只需为您创建的每个弹出窗口继续在 MAP 中添加条目。 在地图中

  1. 第一个参数 用于显示弹出窗口的元素。 (如果是按钮)

  2. 第二个参数 模态弹出窗口本身

答案 3 :(得分:1)

基于@junkfoodjunkie 的回答的一些改进

没有 JS 的 html 和 CSS 中的弹出/模态:

.button {
    display: inline-block;
    border: 1px solid;
    border-color: #012766;
    background: #012766;
    padding: 10px 16px;
    border-radius: 4px;
    color: #ffffff;
}
[id^=modal] {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
}
[id^=modal]:target {
    display: block;
}
input[type=checkbox] {
    position: absolute;
    clip: rect(0 0 0 0);
}
.popup {
    width: 100%;
    height: 100%;
    z-index: 99999;
}
.popup__overlay {
    position: fixed;
    z-index: 1;
    display: block;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: #000000b3;
}
.popup__wrapper {
    position: fixed;
    z-index: 9;
    width: 80%;
    max-width: 1200px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 8px;
    padding: 58px 32px 32px 32px;
    background: #fff;
}
.popup__close {
    position: absolute;
    top: 16px;
    right: 26px;
}
<a class="button" href="#modal1">Open modal 1</a>

<div class="popup" id="modal1">
    <a class="popup__overlay" href="#"></a>
    <div class="popup__wrapper">
        <a class="popup__close" href="#">Close icon here</a>
        <p>POPUP 1 : CONTENT HERE</p>
    </div>
</div>


<a class="button" href="#modal2">Open modal 2</a>

<div class="popup" id="modal2">
    <a class="popup__overlay" href="#"></a>
    <div class="popup__wrapper">
        <a class="popup__close" href="#">Close icon here</a>
        <p>POPUP 2 : CONTENT HERE</p>
    </div>
</div>

答案 4 :(得分:1)


我的提议

const btns = document.getElementsByClassName('btn');
const spans = document.getElementsByClassName('close');
const modals = document.getElementsByClassName('modal');

[...btns].forEach((btn, ind) => {
  btn.onclick = () => (modals[ind].style.display = 'block');
});

[...spans].forEach((span, ind) => {
  span.onclick = () => (modals[ind].style.display = 'none');
});

window.onclick = (e) => {
  [...modals].forEach((modal) => {
    if (e.target === modal) {
      modal.style.display = 'none';
    }
  });
};  

如果您不使用 ID 而只使用类名 而不是

<button id="myBtn">Open Modal</button>

<div id="myModal" class="modal">

<span class="close">×</span>

就用

<button class="btn">Open Modal</button>

<div class="modal">

<span class="close">x</span>

您可以将所有打开按钮存储在 HTML 集合中

const btns = document.getElementsByClassName('btn');

将 HTML 集合转移到数组中

[...btns]

为数组中的每个按钮添加 onclick 事件

.forEach((btn, ind) => {
  btn.onclick = () => (modals[ind].style.display = 'block');
});

你对 span(关闭按钮)做同样的事情

答案 5 :(得分:0)

  • 您为两个模态触发按钮分配了相同的ID。不同的元素不应具有相同的Id。

  • 在JavaScript代码中,您总是选择一个元素(一个关闭按钮,一个打开按钮等)。

我会说这是HTML / JS初学者的错误。这可行:

// Get the button that opens the modal
var btn = document.querySelectorAll("button.modal-button");

// All page modals
var modals = document.querySelectorAll('.modal');

// Get the <span> element that closes the modal
var spans = document.getElementsByClassName("close");

// When the user clicks the button, open the modal
for (var i = 0; i < btn.length; i++) {
 btn[i].onclick = function(e) {
    e.preventDefault();
    modal = document.querySelector(e.target.getAttribute("href"));
    modal.style.display = "block";
 }
}

// When the user clicks on <span> (x), close the modal
for (var i = 0; i < spans.length; i++) {
 spans[i].onclick = function() {
    for (var index in modals) {
      if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";    
    }
 }
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
     for (var index in modals) {
      if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";    
     }
    }
}
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}
<h2>1st Modal</h2>

<!-- Trigger/Open The Modal -->
<button class="modal-button" href="#myModal1">Open Modal</button>

<!-- The Modal -->
<div id="myModal1" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

<h2>2nd Modal</h2>

<!-- Trigger/Open The Modal -->
<button class="modal-button" href="#myModal2">Open Modal</button>

<!-- The Modal -->
<div id="myModal2" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

答案 6 :(得分:0)

Denis Mysenko 给出的优秀答案的更新:

我的 JS 曾经是(对于一个模态):

let modal = document.getElementById('about-modal');
let btn = document.getElementById('about-modal-btn');
let close = document.getElementsByClassName('close')[0];

btn.onclick = function() {
    modal.style.display = 'block';
}

close.onclick = function() {
    modal.style.display = 'none';
}

window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = 'none';
    }
}

window.onkeydown = function(event) {
    if (event.key == 'Escape') {
        modal.style.display = 'none';
    }
}

我的新 JS(取自丹尼斯的回答:

let modals = document.getElementsByClassName('modal');
let modalBtns = document.getElementsByClassName('modal-btn');
let closeBtns = document.getElementsByClassName('close');

for(let modalBtn of modalBtns) {
    modalBtn.onclick = function(event) {
        document.querySelector(event.target.getAttribute('href') ).style.display = 'block';
    }
}

for(let closeBtn of closeBtns) {
    closeBtn.onclick = function(event) {
        event.target.parentNode.parentNode.style.display = 'none';
    }
}

window.onclick = function(event) {
    if(event.target.classList.contains('modal') ) {
        for(let modal of modals) {
            if(typeof modal.style !== 'undefined') {
                modal.style.display = 'none';    
            }
        }
    }
}

window.onkeydown = function(event) {
    if (event.key == 'Escape') {
        for(let modal of modals) {
            modal.style.display = 'none';
        }
    }
}

希望这能在未来对其他人有所帮助。我清理了一些不一致和其他小东西,并简化了代码和变量名称,使用es6语法等。 可能有人也可以将代码用于单个模态。模态结构示例:

<button id="settings-modal-btn" class="modal-btn" href="#settings-modal">Settings</button>
<div id="settings-modal" class="modal">
    <div class="modal-content">
        <button class="close">&times;</button>
        <p>Content here...</p>
    </div>
</div>

答案 7 :(得分:-1)

在您的JSFiddle上,请确保使用class="myBtn"代替id="myBtn",然后才能使用。

以下是完整的工作代码:

HTML:

<h2>1st Modal</h2>

<!-- Trigger/Open The Modal -->
<button class="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

<h2>2nd Modal</h2>

<!-- Trigger/Open The Modal -->
<button class="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal2" class="modal">

  <!-- Modal content -->
  <div class="modal2-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

<强> JS:

// Get the modal
var modal = document.getElementsByClassName('modal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");


// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");

// When the user clicks the button, open the modal 
btn[0].onclick = function() {
    modal[0].style.display = "block";
}

btn[1].onclick = function() {
    modal[1].style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span[0].onclick = function() {
    modal[0].style.display = "none";
}

span[1].onclick = function() {
    modal[1].style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}