在动画结束时不显示任何内容

时间:2017-03-29 09:34:00

标签: javascript jquery html css object

我试图在动画结束时让元素消失,但它不起作用,有人可以解释如何在元素消失的情况下制作退出动画吗?:

var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event){
    event.target.style.animation = "changeOpacity 1s linear";
    if(event.target.style.opacity === 0){
        event.target.style.display = "none";
    }
}
.container .test {
  text-align: center;
  padding: 100px;
  color: #fff;
  background-color: #00f;
  max-width: 500px;
  -webkit-animation-fill-mode: forwards;
          animation-fill-mode: forwards;
}

@-webkit-keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
@keyframes changeOpacity {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

<body>
    <div class="container">
        <div class="test" id="test">Custom Text</div>
    </div>
<script src="main.js"></script>
</body>

3 个答案:

答案 0 :(得分:2)

由于您已标记为jQuery,因此使用.fadeOut()更容易吗?在动画结束后,元素的display属性被设置为none

&#13;
&#13;
$('#test').click(function(){
  $(this).fadeOut();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test'>Text</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您的问题是因为animation-fill-mode没有被尊重,因为您通过直接在元素本身上设置animation规则来覆盖它。

要解决此问题,请修改JS代码以在元素上添加类,并在其中放置animation规则以及所需的填充模式:

var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);

function displayOpacity(event) {
    this.classList.add('changeOpacity');
}
.container .test {
    text-align: center;
    padding: 100px;
    color: #fff;
    background-color: #00f;
    max-width: 500px;
}

.changeOpacity {
    animation: changeOpacity 1s linear forwards;
}

@-webkit-keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}
@-webkit-keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}
@keyframes changeOpacity {
    0% {  opacity: 1; }
    100% { opacity: 0; }
}
<div class="container">
    <div id="test" class="test">
        Test
    </div>
</div>

答案 2 :(得分:1)

动画时间为1秒

event.target.style.animation = "changeOpacity 1s linear";

所以只是暂停

setTimeout(function(){
    event.target.style.display = "none";
},1000)