CSS 强制动画在单击、活动或焦点时完全完成?

问题描述 投票:0回答:2

鉴于:

.button_focus, .button_active {
  width: 8rem;
  height: 5rem;
  background-color: #e4e7eb;
}

.button_focus:focus,
.button_active:active {
  animation-name: clickAnimation;
  animation-duration: 250ms;
  animation-timing-function: ease-in-out;
}

@KeyFrames clickAnimation {
    0.00% { background-color: #d5d7da; }
   14.29% { background-color: #ced0d3; }
   28.57% { background-color: #bbbbbb; }
   42.86% { background-color: #b1b2b3; }
   57.14% { background-color: #b1b2b3; }
   71.43% { background-color: #bbbbbb; }
   85.71% { background-color: #ced0d3; }
  100.00% { background-color: #d5d7da; } 
}
<div class="contianer">
  <button class="button_focus">
    focus
  </button>
  <button class="button_active">
    active
  </button>
</div>

我想找到一种方法,能够让垃圾点击按钮和动画每次都得到完全处理。目前,使用

:focus
伪类,我需要单击按钮然后单击离开,以便当我再次单击按钮时重新初始化动画。

相反,如果我使用

:active
伪类,则每次连续单击时都会播放动画,但并未“完全”完成。我需要按下250ms按钮才能完全完成动画。

SO上有一些关于这个问题的帖子,解决方案似乎是使用JS添加一个动画类,然后将其删除,但在大多数帖子中,问题都涉及悬停。就我而言,这只是一次点击,所以我不明白如何添加动画类并在某个时候删除它。我想我只是很困惑。

有人有什么想法或建议吗?

css css-animations
2个回答
2
投票

使用JS我们可以监听按钮的点击,添加一个设置动画的类。

我们永久监听按钮上的animationend 事件,当触发该事件时,我们删除该类。这样,动画在完成之前不会受到“干扰”,但我们确实需要将其删除,以便在下次单击时可以再次设置它(否则,如果设置没有更改,CSS 会认为它已经完成了)。

const button = document.querySelector('.button_click'); button.addEventListener('click', function() { button.classList.add('clicked'); }); button.addEventListener('animationend', function() { button.classList.remove('clicked'); });
.button_click {
  width: 8rem;
  height: 5rem;
  background-color: #e4e7eb;
  animation-name: none;
}

.button_click.clicked {
  animation-name: clickAnimation;
  animation-duration: 250ms;
  animation-timing-function: ease-in-out;
}

@KeyFrames clickAnimation {
  0.00% {
    background-color: #d5d7da;
  }
  14.29% {
    background-color: #ced0d3;
  }
  28.57% {
    background-color: #bbbbbb;
  }
  42.86% {
    background-color: #b1b2b3;
  }
  57.14% {
    background-color: #b1b2b3;
  }
  71.43% {
    background-color: #bbbbbb;
  }
  85.71% {
    background-color: #ced0d3;
  }
  100.00% {
    background-color: #d5d7da;
  }
}
<div class="contianer">
  <button class="button_click">
    click me
  </button>
</div>


0
投票

只需确保在 CSS 文件中的 :focus 规则之后键入 :active 规则

© www.soinside.com 2019 - 2024. All rights reserved.