首页 > 解决方案 > 在页面加载时打开 javascript 模式

问题描述

我有一个由按钮启动的模式。除了按钮之外,我还需要它在页面加载时启动。有什么办法可以在我当前的代码范围内实现这一点?

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

标签: javascriptjquerymodal-dialog

解决方案


当您获得模式时 - 只需将样式设置为显示:块

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

或者更好 - 拥有具有样式的类,然后添加或删除类以显示/隐藏模式。您可以将 display: none 设置为默认值,然后设置一个 allwos display: 在添加时阻止的“活动”类。

显示模态

modal.classList.add('active') 

隐藏模态

modal.classList.remove('active') 


// css 
#myModal{
display: none;
}

#myModal.active {
display: block;
}

推荐阅读