我在关闭模式弹出窗口时遇到了一些问题,其中一个关闭了,而另一个则没有。我不太确定问题出在哪里,尽管这一定是微不足道的。我刚刚开始认真学习JS,因此希望获得一些帮助。 我必须补充一点,这两种模式都很好。
// Get the modal
var modal = document.getElementById('modal');
// Get the button that opens the modal
var btn = document.getElementById("regbtn");
// Get the modal
var signinmodal = document.getElementById('signinmodal');
// Get the button that opens the modal
var signinbtn = document.getElementById("signinbtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on the button, open the modal
signinbtn.onclick = function() {
signinmodal.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";
}
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
signinmodal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target === signinmodal) {
signinmodal.style.display = "none";
}
}
答案 0 :(得分:1)
当您两次分配window.onclick = ...
时,您将覆盖对其的最后一次分配,就像您将一个值分配给变量一样:
val = 5;
val = 7; // 5 is now gone
您应该将它们组合到同一函数调用中,以确保事件将持续存在
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
if (event.target === signinmodal) {
signinmodal.style.display = "none";
}
}
span标签也是如此
span.onclick = function() {
modal.style.display = "none";
signinmodal.style.display = "none";
}