如何获得淡入模态效果?

时间:2017-08-10 03:38:20

标签: javascript html css

https://jsfiddle.net/7doq0vkL/1/

我试图让这个JSFiddle淡入淡出并逐渐消失。它正在工作,但在关闭后它还没有再次打开。我尝试将div设置为显示:在900ms之后没有,但是停止了关闭淡入淡出工作。任何人都可以看到需要对JSFiddle进行哪些更改才能让它再次打开?

compat-libvncserver

CSS

<div class="w3-container">
  <h2>Animated Modal</h2>

  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Fade In Modal</button>

  <div id="id01" class="w3-modal w3-animate-opacity">
    <div class="w3-modal-content w3-card-4">
      <header class="w3-container w3-teal">
        <span onclick="document.getElementById('id01').classList.add('w3-animate-show');" class="w3-button w3-large w3-display-topright">&times;</span>
        <h2>Modal Header</h2>
      </header>
      <div class="w3-container">
        <p>Some text..</p>
        <p>Some text..</p>
      </div>
      <footer class="w3-container w3-teal">
        <p>Modal Footer</p>
      </footer>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:5)

将元素保留在display: none; opacity: 0;的页面上将保持页面上该元素的布局,覆盖按钮。一旦元素淡出,您可以使用animationend事件来应用display: none

&#13;
&#13;
var id01 = document.getElementById('id01');

document.querySelector('.close').addEventListener('click', function() {
  id01.classList.add('w3-animate-show');
})

id01.addEventListener('animationend', function() {
  if (this.classList.contains('w3-animate-show')) {
    this.style.display = 'none';
    this.classList.remove('w3-animate-show')
  }
});
&#13;
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<style>
 .w3-animate-opacity {
   animation: opac 0.8s
 }
 
 @keyframes opac {
   from {
     opacity: 0
   }
   to {
     opacity: 1
   }
 }
 
 .w3-animate-show {
   animation: show 0.8s;
   animation-fill-mode: forwards;
 }
 
 @keyframes show {
   0% {
     opacity: 1
   }
   100% {
     opacity: 0
   }
 }
</style>
<div class="w3-container">
  <h2>Animated Modal</h2>

  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Fade In Modal</button>

  <div id="id01" class="w3-modal w3-animate-opacity">
    <div class="w3-modal-content w3-card-4">
      <header class="w3-container w3-teal">
        <span class="w3-button w3-large w3-display-topright close">&times;</span>
        <h2>Modal Header</h2>
      </header>
      <div class="w3-container">
        <p>Some text..</p>
        <p>Some text..</p>
      </div>
      <footer class="w3-container w3-teal">
        <p>Modal Footer</p>
      </footer>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

点击此链接,您将知道如何执行此操作:https://jsfiddle.net/7doq0vkL/1/

您的代码的主要问题是您没有为模态设置display:none,其次,点击该按钮时,您必须删除该淡化类"w3-animate-show"