2016-11-30 92 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

相关问题