使用JavaScript即时结束CSS动画

时间:2018-01-13 09:27:12

标签: javascript html css animation

我有一个分配了CSS动画的输入框,所以当页面加载时,它有一个很好的淡入动画。

CSS:

#search-box {
    /* ... */
    animation: 2s fade-in
}

@keyframes fade-in {
    from { opacity: 0 }
    to { opacity: 1 }
}

在某些情况下,当加载页面时(存在URL参数时),我希望输入框的CSS动画停止并立即将不透明度置于1

我尝试使用animation-play-state并试图用!important覆盖不透明度,但没有运气。

使用Javascript:

let endAnimation = // ... boolean
if (endAnimation) {
    let elem = document.getElementById('search-box');
    // End the animation and set opacity to 1 somehow...
}

HTML:

<input id="search-box">

1 个答案:

答案 0 :(得分:3)

您可以在单独的类中制作动画,只需删除此类即可停止动画:

let stop = function() {
  let elem = document.getElementById('search-box');
  elem.classList.remove('animate');
}
#search-box {}

.animate {
  animation: 5s fade-in;
}

@keyframes fade-in {
  from {
    opacity: 0
  }
  to {
    opacity: 1
  }
}
<input id="search-box" class="animate">
<button onclick='stop()'>stop!</button>

或者只是取消设置动画属性:

let stop = function() {
  let elem = document.getElementById('search-box');
  elem.style.animation='unset';
}
#search-box {
  animation: 5s fade-in;
}

@keyframes fade-in {
  from {
    opacity: 0
  }
  to {
    opacity: 1
  }
}
<input id="search-box" class="animate">
<button onclick='stop()'>stop!</button>