我有一个通过按钮启动的模式。除了按钮之外,我还需要它在页面加载时启动。有什么方法可以在当前代码范围内实现这一目标?
// 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";
}
}
答案 0 :(得分:1)
获得模态后,只需将样式设置为显示:块
var modal = document.getElementById('myModal');
modal.style.display = "block"
或更妙的是-拥有具有样式的类,然后添加或删除这些类以显示/隐藏模态。您可能已经显示:没有设置为默认值,然后设置了一个“活动”类,当添加时将全部显示:阻止。
显示模式
modal.classList.add('active')
隐藏模式
modal.classList.remove('active')
// css
#myModal{
display: none;
}
#myModal.active {
display: block;
}