2017-05-06 50 views
0

在站點上測試多個模塊。兩種模式都可以打開。但是,第二個模態(contmodal)不會關閉。這似乎也造成了導致其他JS破裂的問題。使用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"; 
    } 
} 
+0

代碼似乎沒有問題。你有沒有看到在控制檯中是否有任何錯誤? – Alex

+0

看看這個https://github.com/EasonWang01/react-pure-css-modal 不需要使用js – seasonqwe

+0

問題出在哪裏當用戶點擊(x)時,關閉模式?或者當用戶點擊模式外的任何地方時,關閉它? –

回答

0

你的代碼看起來不錯。 下面是這個例子中,你應該是指 - 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

+0

不會關閉「contact-modal」。這是一個很好的例子。如果用戶在div外部單擊,我可以添加JS來關閉模式。 '// *獲取時事通訊模式 var modal1 = document.getElementById('openModal1'); var modal2 = document.getElementById('openModal2'); //當用戶點擊的模態的以外的任何地方,關閉它 window.onclick =函數(事件){ 如果(event.target == modal1){ modal1.style.display = 「無」; } if(event.target == modal2){ modal2.style.display =「none」; } }' 不幸的是,這不允許用戶再次點擊它來重新打開它。 –

0

添加以下JavaScript來阿比納夫Ralhan的解決方案:

//* Get the Newsletter Modal 
var modal1 = document.getElementById('openModal1'); 
var modal2 = document.getElementById('openModal2'); 

// When the user clicks anywhere outside of the modal, close it 
window.onclick = function(event) { 
    if (event.target == modal1 || event.target == modal2) { 
    window.location.href = "#"+close; 
    } 
}