模态正在关闭,但不打开

时间:2019-07-17 16:34:59

标签: javascript

打开模态的按钮无法正常工作。我可以关闭模​​式,但是因为按钮不起作用而无法打开。

模式也可以立即打开,但最初应该关闭。而且只有在我单击打开按钮模态后,才能打开。

My codepen to see it at work

var modal = document.getElementsByClassName("modal-inner");
var btn = document.getElementsByClassName("open-button");
var close = document.getElementsByClassName("close-button")[0];

btn.onclick = function () {
    modal[0].style.display = "block";
}

close.onclick = function () {
    modal[0].style.display = "none";
}

1 个答案:

答案 0 :(得分:2)

您的按钮带有id“打开按钮”,但正在使用getElementsByClassName

或者使用getElementById或将按钮的类更改为“打开按钮”

var modal = document.getElementsByClassName("popup-inner");
var btn = document.getElementById("open-button");
var close = document.getElementsByClassName("close-button")[0];

btn.onclick = function () {
    modal[0].style.display = "block";
}

close.onclick = function () {
    modal[0].style.display = "none";
}
.popup-inner {border: 1px solid black; height:200px; width:400px; background-color: pink;}
p {text-align: center; font-size: 36px;}
.close-button { position: relative; z-index: 100; float:right; margin-right:5px; margin-top: 5px;}
<button id="open-button">click on me</button>
<div class="popup-inner">
  <button class="close-button">X</button>
  <p>My modal</p>
</div>