【问题标题】:Display none at the end of animation动画结束时不显示
【发布时间】:2017-08-22 17:10:27
【问题描述】:

我正在尝试使元素在动画结束时消失,但它不起作用,有人可以解释如何使元素在结束时消失的退出动画吗?:

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>

【问题讨论】:

  • 发布您的 html。

标签: javascript jquery html css object


【解决方案1】:

既然你已经标记了jQuery,那么使用.fadeOut() 不是更容易吗?动画结束后,元素的display 属性被设置为none

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

【讨论】:

  • 这会更容易,但是使用 CSS 的动画更可靠、更流畅,因为它的硬件加速了,而 JS 没有。
  • @RoryMcCrossan 同意,但这只是解决这种情况的一种可能方法。如果 OP 不会标记jQuery,我不会发布它。无论如何,这是非常友好和简单的解决方案,尤其是对于初学者。
  • 不用担心,我只是提到它,因为你似乎在问为什么在这种情况下你会选择 CSS 而不是 jQuery。
【解决方案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>

【讨论】:

    【解决方案3】:

    动画时间为1秒

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

    所以只需要超时

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多