Открыть модальный javascript при загрузке страницы - PullRequest
0 голосов
/ 09 января 2019

У меня есть модал, который запускается кнопкой. В дополнение к кнопке она мне нужна и для загрузки страницы. В любом случае, я могу достичь этого в рамках моего текущего кода?

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

1 Ответ

0 голосов
/ 09 января 2019

Когда вы получаете модал - просто установите стиль отображения: block

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

или еще лучше - есть классы, которые имеют стиль, а затем добавьте или удалите классы, чтобы показать / скрыть модальный стиль. Вы могли бы иметь display: none, установленный по умолчанию, а затем «активный» класс, который allwos отображает: block при его добавлении.

Показать модал

modal.classList.add('active') 

чтобы скрыть модал

modal.classList.remove('active') 


// css 
#myModal{
display: none;
}

#myModal.active {
display: block;
}
...