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";
}
}
}
如果我刪除功能,它不會出現在所有的,如果我嘗試代碼在jsfiddle它的作品,但在我的崇高它不 –
@MartijnHermsen由於上述代碼在SO這裏工作,你一定錯過了一些東西。請注意,您的腳本需要運行_after_頁面加載,最後添加在您的頁面或使用正文onload處理程序 – LGSon
@MartijnHermsen更新我的答案與頁面加載 – LGSon