点击即可来回运行CSS动画 [英] Run css animation back and forth on clicks

查看:64
本文介绍了点击即可来回运行CSS动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用css @keyframes ,我试图在单击元素时将一些动画附加到元素上.

With css @keyframes I'm trying to attach some animation to an element when it is clicked.

.animate {
    animation-name: action;
    animation-duration: 2s;
    animation-timing-function: linear;
    background-color: green;
} 

@keyframes action {
    0% {
        background-color: gray; 
    }  

   50% {
       background-color: red;
   }

   100% {
       background-color: green;
   }
}

演示

在单击时添加 .animate 类,该框从灰色变为绿色.但是现在,当我再次单击它(切换功能)时,我想重新设置为灰色.我尝试通过 animation-direction:reverse 使用相同的动画,但是没有播放动画.动画最初不应播放(我遇到过几次).有什么建议我可以实现吗?

The .animate class is added on click, and the box animates from gray to green. But now I would like to animate back to gray when I click it again (toggle functionality). I tried using the same animation using animation-direction: reverse but no animation was played. The animation should not play initially (I encountered that a couple of times). Any suggestion how I can achieve that?

推荐答案

使用动画处理这种开/关更改总是很棘手,并且很难流畅且无缝地处理重复的更改.

Handling this kind of on/off changes with animations is always tricky, and it is very difficult to handle the repeated changes smoothly and seamlessly.

对于您的情况,我建议将其更改为单个过渡.在这种情况下,浏览器可以更好地处理开/关部分.要通过过渡实现背景色的双重更改,请创建3种颜色的渐变,然后更改渐变位置:

For your case, I would suggest to change it to a single transition. Browser handle much better the on/off part in this case. To achieve a double change in the background color with a transition, create a gradient with 3 colors, and change the gradient position:

const div = document.querySelector('.test')
div.addEventListener('click', (e) => {
   div.classList.toggle('play');
})

.test {
  border: solid 1px black;
  margin: 10px;
  height: 100px;
  width: 100px;
  background-image: linear-gradient(gray 0%, gray 20%, blue 40%, blue 60%,
   red 80%, red 100%);
  background-size: 100% 9000%;
  background-repeat: no-repeat;
  background-position: center top;
  transition: background-position .3s;
}

.play {
  background-position: center bottom;
}

<div class="test">
</div>

这篇关于点击即可来回运行CSS动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆