简体   繁体   English

在页面加载时打开JavaScript模式

[英]Open javascript modal on page load

I have a modal that is launched by a button. 我有一个由按钮启动的模式。 In addition to the button, I need it to launch on page load as well. 除了按钮之外,我还需要它在页面加载时启动。 Any way I can achieve this within confines of my current code? 有什么办法可以在当前代码的范围内实现这一目标?

// 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";
  }
}

When you get the modal - simply set the style to display: block 获得模态后,只需将样式设置为display:block

var modal = document.getElementById('myModal');
modal.style.display = "block"

or better yet - have classes that have the styling and then add or remove the classes to show / hide the modal. 或更好的是-拥有具有样式的类,然后添加或删除这些类以显示/隐藏模态。 You could have display: none set as the default and then an "active" class that allwos display: block when its added. 您可能已经显示:没有将其设置为默认值,然后添加了一个“活动”类,该类在添加时将显示:阻止。

To show the modal 显示模态

modal.classList.add('active') 

to hide the modal 隐藏模态

modal.classList.remove('active') 


// css 
#myModal{
display: none;
}

#myModal.active {
display: block;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM