2017-02-11 29 views
0

我有一個網頁中的2個彈出式模式,如果用戶點擊模式外的任何地方,我想關閉它。問題是隻有第一個作品第一個沒有。Java腳本雙模式無法關閉

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

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

回答

0

對於兩種彈出​​模式都使用相同的點擊功能。

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

您正在重寫第一個onclick。

只需一個onclick窗口,檢查模式類型,並根據您設置它顯示無。

+0

我知道我重寫了代碼。但是我有兩個變量modal1和modal2,我該怎麼樣關閉兩個模態?你能提供一個代碼片段嗎? –

0

你正在重寫第一個onclick與第二個。你可以這樣做;

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