javascript - 使用 JS 关闭多个模态框

标签 javascript html css

在站点上测试多个模式。两种模式都可以正常打开。但是,第二个模态(contmodal)不会关闭。此外,这似乎会产生导致其他 JS 中断的问题。

//* Get the Newsletter Modal
var newsmodal = document.getElementById('newsletter-modal');
var contmodal = document.getElementById('contact-modal');

// Get the button that opens the modal
var newsbtn = document.getElementsByClassName("signup-button")[0];
var editbtn = document.getElementsByClassName("contact-button")[0];

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

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

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

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

最佳答案

您的代码看起来不错。 这是您应该引用的示例 - http://jsfiddle.net/3Vykc/

<a href="#openModal1">Box 1</a>
<div id="openModal1" class="modalDialog">
<div>
   <a href="#close" title="Close" class="close">X</a>
   <h2>Modal Box 1</h2>
   <p>This is a sample modal box that can be created using the powers of CSS3.    </p>
   <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
</div>
</div>
<a href="#openModal2">Box 2</a>

<div id="openModal2" class="modalDialog">
<div>
    <a href="#close" title="Close" class="close">X</a>
    <h2>Modal Box 2</h2>
    <p><strong>Box 2</strong></p>
    <p>yadda yadda</p>
</div>

更多引用:

Using multiple modal dialogs in one page

How can I close multiple bootstrap modals with the close button on the last popped modal

关于javascript - 使用 JS 关闭多个模态框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43816671/

相关文章:

c# - 如何在 ASP.NET 中从数据库加载图像作为 Web 浏览器中的文件?

javascript - node.js 中的 async.eachSeries

javascript - 如何使用javascript调用文本字段中文本更改的函数

jquery - 如何使DIV在不可点击的区域可点击?

html - 网站与 IE 和 firefox 不兼容

javascript - 什么是传递类型、通过一些条件并返回对象的良好设计模式

Javascript下雪函数?

javascript - 使用 ng-show 启用我的 div

html - 对特定的 div 元素实现 z-index

css - 在具有必填属性的输入字段上执行 display none 仍然会使表单无效