如何将CSS中定义的动画应用于点击类?

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

我有一个班级,只是一个简单的绿色广场。我做了一个简单的摇动动画,但我没有设法找到一种方法来点击动画。我已经尝试了jQuery和纯CSS解决方案,到目前为止还没有任何工作。动画:

@keyframes hit {
40% {transform: scale(1,1);transform: rotateX(-20deg);transform: rotateY(20deg);transform:rotate(-5deg);}
60% {transform: scale(1.1,1.1);transform: rotateX(20deg);transform: rotateY(-20deg);        }

和班级:

target-container {
animation-name: none;
animation-duration:0.3s;}

我最接近它的工作是使用这个功能:

function hitTarget() {
    target.style.animationName="hit";
    setTimeout(stopAnimation,300);
    function stopAnimation() {
        target.style.animationName="none";
    }
}

target.addEventListener("click",function() {
hitTarget();},false);
javascript jquery html css animation
1个回答
1
投票

您的代码存在一些问题 - 不确定它们是否是将其纳入问题或部分实际代码的结果。那么让我们来看看吧。

  1. 我想我必须在CSS中修复一些语法错误 - 缺少关闭}(括号)。
  2. 此外,要定义多个transforms,只需在单个transform样式中列出所有变换。像transform: rotate(2deg) scale(1.2)
  3. 我们将传递hitTarget函数作为对事件监听器的回调,而不是传递调用hitTarget函数的匿名函数。
  4. 最后,我建议添加/删除一个应用动画的CSS类,而不是添加/删除animation-name

所有清理和工作都在这里:

function hitTarget(event) {
  const animationClass = "withAnimation";
  event.target.classList.add(animationClass);
  setTimeout(stopAnimation, 300);

  function stopAnimation() {
    event.target.classList.remove(animationClass);
  }
}

document.querySelector(".target-container").addEventListener("click", hitTarget, false);
@keyframes hit {
  40% {
    transform: scale(1, 1) rotateX(-20deg) rotateY(20deg) rotate(-5deg);
  }
  60% {
    transform: scale(1.1, 1.1) rotateX(20deg) rotateY(-20deg);
  }
}

.target-container {
  width: 100px;
  height: 100px;
  background-color: green;
}

.withAnimation {
  animation-name: hit;
  animation-duration: 0.3s;
}
<div class="target-container"></div>
© www.soinside.com 2019 - 2024. All rights reserved.