2017-06-02 95 views
1

我在这里跟着这个问题:https://www.w3schools.com/howto/howto_css_modals.asp 问题是当我创建两个这样的模块时,第一个模块在点击它之外时不会关闭。这里的的jsfiddle: https://jsfiddle.net/j1smeu3c/当你点击它之外时,多个模块不会关闭

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

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

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

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

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

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

////////////////////////// 

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

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

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

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

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

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

在你关闭功能,它不应该是如果(event.target = modal2!),或者是只是一个错字?目前只有当您点击模式时才会关闭,而不是在您点击模式之外时关闭 – maembe

回答

2

你的window.onclick秒声明覆盖了第一个。你应该在两个函数中设置两个检查。

window.onclick = function(event) { 
    if (event.target == modal2) { 
     modal2.style.display = "none"; 
    } 
    if (event.target == modal1) { 
     modal1.style.display = "none"; 
    } 

} 
0

您有两个window.onclick函数。删除其中的一个,让一个像这样的:

window.onclick = function(event) { 
    if (event.target == modal1) { 
     modal1.style.display = "none"; 
    } 
    if (event.target == modal2) { 
     modal2.style.display = "none"; 
    } 
} 
相关问题