3

var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close");
var buttons = document.getElementsByClassName("myBtn")

for (var i = 0; i < span.length; i++) {
  span[i].onclick = function() {
    var id = this.getAttribute('data-modal');
    var modal = document.getElementById(id);
    modal.style.display = 'none';
  }
}

for (var i = 0; i < buttons.length; i++) {
	buttons[i].onclick = function() {
    var id = this.getAttribute('data-modal');
    var modal = document.getElementById(id);
    modal.style.display = 'block';
  }
}

window.onclick = function(event) {
  var isModal = (' ' + event.target.className + ' ').indexOf(' modal ') > -1;
  if (isModal) {
    event.target.style.display = "none";
  }
}
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 100000; /* Sit on top */
    padding-top: 172px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    position: relative;
    /* background-color: #fefefe; */
    margin: auto;
    padding: 0;
    /* border: 1px solid #888; */
    width: 684px;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s;
}

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* The Close Button */
.close {
    margin-top: -11px;
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="myBtn" data-modal="myModal1" >Open Modal</button>
<div id="myModal1" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close" data-modal="myModal1">&times;</span>
     
    </div>
    <div class="modal-body">
       text
    </div>
  </div>
</div>

Есть модальное окно, открывается оно с анимацией, а закрывается без нее. Как реализовать чтобы оно и закрывалось с анимацией? (Снизу-вверх).

1
  • Продолжайте разбираться с анимацией. Animation-fill-mode: forwards; Воспользуйтесь в анимации этим правилом. 3 янв 2018 в 7:05

3 ответа 3

2

Как например:

$('.close').on('click', function(){
  var $this = $(this),
      modal = $this.closest('.modal'); 
  
  modal.toggleClass('show hide');
  
  setTimeout(function(){
    modal.removeClass('hide');
  }, 400);
});


$(".myBtn").on('click', function(e){
  e.preventDefault();  
  
  var $this = $(this),
      id = $this.data('modal'),
      modal = $('#'+id);
  
  if(!modal.hasClass('show')){
    modal.addClass('show');
   
  }else {
    modal.removeClass('show');
  }   
  
});


$(document).click(function (e) {
  var container = $('.modal');
  if ($(e.target).is('.modal')) {
    
    container.toggleClass('show hide');
  
    setTimeout(function(){
      container.removeClass('hide');
    }, 400);
  }
});
* {
  box-sizing: border-box;
}

.modal {
  display: none; 
  position: fixed; 
  z-index: 100000; 
  padding-top: 172px;
  left: 0;
  top: 0;
  width: 100%; 
  height: 100%; 
  overflow: auto; 
  padding: 1rem;
  background-color: rgb(0,0,0); 
  background-color: rgba(0,0,0,0.4);
}

.modal.show {
  display: block;
}

.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  max-width: 684px;
  width: 100%;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),
    0 6px 20px 0 rgba(0,0,0,0.19); 
  
  transform: translateY(-300px);  opacity:0;
}



.modal.show .modal-content {
  animation: modalShow .4s both;
}

.modal.hide .modal-content {
  animation: modalHide .4s both;
}

.modal.hide {
  display: block;
}

@keyframes modalShow {
  /* from { transform: translateY(-300px);  opacity:0; } */
  to { transform: translateY(300px);  opacity:1; }
}


@keyframes modalHide {
  from { transform: translateY(300px);  opacity:1; }
  to { transform: translateY(-300px);  opacity:0; }
}

.close {
  font-size: 28px;
  font-weight: bold;
  
  cursor: pointer;
  position: absolute;
  right: 0;
  left: 100%;
  top: -14px;
  width: 14px;
  padding-right: 0;
  text-align: center;
  line-height: 28px;
  cursor: pointer !important;
  color: #fff;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  
<button class="myBtn" data-modal="myModal1" >Open Modal</button>
  
<div id="myModal1" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
     
    </div>
    <div class="modal-body">
       text
    </div>
  </div>
</div>

Смысл в том, что при клике на "закрыть" должен добавляться еще один класс, отвечающий за анимированное закрытие.

Если задавать просто dispaly: none, то все моментально исчезает вместе с содержимым.

А еще лучше использовать плагин для модального окна, как например magnific popup, его легко настроить на анимированный показ и исчезание.

1

Можно попробовать вообще одним CSS обойтись, может такой вариант подойдёт
(это скрытый checkbox)

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
 
  -webkit-transition: background .5s;
  -moz-transition: background .5s;
  -o-transition: background .5s;
  transition: background .5s;

}

/* Modal Content */
.modal-content {
  z-index: 100001;
  /*Sit on top */
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  /* border: 1px solid #888; */
  width: 100%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  
  -webkit-transform: translate(0, -500%);
  -ms-transform: translate(0, -500%);
  -o-transform: translate(0, -500%);
  transform: translate(0, -500%);
  
  -webkit-transition: -webkit-transform 1s;
  -moz-transition: -moz-transform 1s;
  -o-transition: -o-transform 1s;
  transition: transform 1s;
}

.modal1:checked~.modal-overlay {
  z-index: 100000;
  background-color: rgba(0, 0, 0, .4);
  /* Black w/ opacity */
}

.modal1:checked~.modal-content {
  -webkit-transform: translate(0, 500%);
  -ms-transform: translate(0, 500%);
  -o-transform: translate(0, 500%);
  transform: translate(0, 500%);
}

.myBtn {
  background: #fff;
  border: #888 solid 1px;
  border-radius: 3px;
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  padding: 8px 15px;
  text-align: center;
  min-width: 60px;
  position: relative;
}

.myBtn:hover,
.myBtn:focus {
  background: #efefef;
}

/* The Close Button */
.close {
  margin-top: -.9em;
  color: gray;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<label class="myBtn" for="myModal1">Open Modal</label>
<div class="modal">
  <input id="myModal1" class="modal1" type="checkbox" hidden>
  <label class="modal-overlay" for="mymodal1"></label>
  <div class="modal-content">
    <div class="modal-header">
      <label class="close" for="myModal1">&times;</label>
    </div>
    <div class="modal-body">
      text
    </div>
  </div>
</div>

-1

Воспользуйтесь например Bootstrap, пример с окном, а также методы по ссылке: https://v4-alpha.getbootstrap.com/components/modal/#live-demo.

А конкретно в Вашем случае за закрытие отвечает эта строчка "modal.style.display = 'none';", вот от неё и пляшите...

2
  • Это не ответ на вопрос. И использовать бутстрап ради анимации закрытия модалки?
    – user212578
    3 янв 2018 в 9:35
  • @Рашен Беар, По крайней мере bootstrap более гибкий в этом плане... Не нужно создавать велосипеды, если они уже созданы! 4 янв 2018 в 11:38

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.