2016-11-30 95 views
1

代碼應該在點擊按鈕後打開一個模式窗口,但是第一次打開它時,需要點擊兩次按鈕才能打開它。 從W3Schools複製一些代碼並修改它以適應我的JS文件後,我遇到了這個問題。Javascript模式需要兩次點擊才能打開

HTML

<h2>Modal Example</h2> 

<!-- Trigger/Open The Modal --> 
<button id="myBtn" onclick="modalFunction()">Open Modal</button> 

<!-- The Modal --> 
<div id="myModal" class="modal"> 

    <!-- Modal content --> 
    <div class="modal-content"> 
    <span class="close">×</span> 
    <p>Some text in the Modal..</p> 
    </div> 

</div> 

Javasript

function modalFunction() { 
// Get the modal 
var modal = document.getElementById('myModal'); 

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

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

// When the user clicks the button, open the modal 
btn.onclick = function() { 
    modal.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"; 
    } 
} 
} 

回答

2

如果您將如預期,將工作以外的功能您的事件負載處理程序。

在這裏,我只是刪除了函數和內聯腳本處理程序。

注意,腳本需要在頁面加載要拼命地跑,而不是之前

window.addEventListener('load', function() { 
 

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

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

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

 
    // When the user clicks the button, open the modal 
 
    btn.onclick = function() { 
 
    modal.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"; 
 
    } 
 
    } 
 

 
});
.modal { 
 
    display: none 
 
}
<h2>Modal Example</h2> 
 

 
<!-- Trigger/Open The Modal --> 
 
<button id="myBtn">Open Modal</button> 
 

 
<!-- The Modal --> 
 
<div id="myModal" class="modal"> 
 

 
    <!-- Modal content --> 
 
    <div class="modal-content"> 
 
    <span class="close">×</span> 
 
    <p>Some text in the Modal..</p> 
 
    </div> 
 

 
</div>

+0

如果我刪除功能,它不會出現在所有的,如果我嘗試代碼在jsfiddle它的作品,但在我的崇高它不 –

+0

@MartijnHermsen由於上述代碼在SO這裏工作,你一定錯過了一些東西。請注意,您的腳本需要運行_after_頁面加載,最後添加在您的頁面或使用正文onload處理程序 – LGSon

+0

@MartijnHermsen更新我的答案與頁面加載 – LGSon

相關問題