在模式关闭CSS上添加SlideDown效果

时间:2018-09-26 12:13:19

标签: css css-animations

我的模态有这种风格,我想知道在哪里以及如何在模态关闭时反转slideUp效果。

var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
    modal.style.display = "block";
}
span.onclick = function() {
    modal.style.display = "none";
}
window.onclick = function(event) {
    if (event.target == modal) {
       modal.style.display = "none";
    }
}
.modal {
    display: none;
    position: fixed;
    overflow: hidden;
    left: 0;
    bottom: 0;
    width: 100%;
    height: auto;
    background-color: black;
    color: white; 
    -webkit-animation: slideIn 0.4s;
    animation: slideIn 0.4s;   
}
@-webkit-keyframes slideIn {
    from {bottom: -300px; opacity: 0} 
    to {bottom: 0; opacity: 1}
}
@keyframes slideIn {
    from {bottom: -300px; opacity: 0}
    to {bottom: 0; opacity: 1}
}

.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}
<div id="myModal" class="modal">

<span class="close">&times;</span>

<p>Some content here</p>

</div>

我基本上想以模态关闭的方式显示它(模态打开和模态关闭的动画相同,仅纯CSS),有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

我将使用在添加和删除类时应用的过渡:

.modal {
  position: fixed;
  overflow: hidden;
  left: 0;
  bottom: 0;
  width: 100%;
  height: auto;
  background-color: black;
  color: white;
  transition: opacity 0.4s, bottom 0.4s;  /* animate these properties */
  opacity: 1;                             /* open state is shown */
}

.modal.closed {
  opacity: 0;     /* close state is hidden and off screen */
  bottom: -300px;
}

.close {
  color: white;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
<div id="myModal" class="modal closed">
  <span class="close">&times;</span>
  <p>Some content here</p>
</div>

<div id="myBtn">click me</div>

<script>
  var modal = document.getElementById('myModal');
  var btn = document.getElementById("myBtn");
  var span = document.getElementsByClassName("close")[0];

  btn.onclick = function(e) {
    e.stopPropagation();                    /* stop event bubbling up to window */
    modal.classList.remove("closed");
  }
  span.onclick = function() {
    modal.classList.add("closed");
  }
  window.onclick = function(event) {
    if (event.target != modal) {
      modal.classList.add("closed");
    }
  }
</script>