为什么我的反弹动画如此跳跃而不是平滑?

人气:484 发布:2022-10-16 标签: css css-animations

问题描述

我需要用纯css实现无限退回效果,所以我引用了this站点,最后做了this。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
.animated {
  -webkit-animation-duration: 2.5s;
  animation-duration: 2.5s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation-timing-function: linear;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
} 

@-webkit-keyframes bounce {
  0%, 20%, 40%, 60%, 80%, 100% {-webkit-transform: translateY(0);}
  50% {-webkit-transform: translateY(-5px);}
} 

@keyframes bounce { 
  0%, 20%, 40%, 60%, 80%, 100% {transform: translateY(0);}
  50% {transform: translateY(-5px);}
} 

.bounce { 
  -webkit-animation-name: bounce;
  animation-name: bounce;
}

#animated-example {
    width: 20px;
    height: 20px;
    background-color: red;
    position: relative;
    top: 100px;
    left: 100px;
    border-radius: 50%;
}

hr {
    position: relative;
    top: 92px;
    left: -300px;
    width: 200px;
}
<div id="animated-example" class="animated bounce"></div>
<hr>

现在,我唯一的问题是弹跳元素需要更长的休息时间才能再次开始弹跳。如何才能使它像我们使用jQuery.animate获得的反弹效果一样平稳反弹?

推荐答案

中间较长的休息时间取决于您的关键帧设置。您当前的关键帧规则意味着实际反弹仅发生在动画持续时间的40%-60%之间(即,动画的1s-1.5s标记之间)。删除这些规则,甚至可以减少animation-duration以满足您的需要。

.animated {
  -webkit-animation-duration: .5s;
  animation-duration: .5s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation-timing-function: linear;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
}
@-webkit-keyframes bounce {
  0%, 100% {
    -webkit-transform: translateY(0);
  }
  50% {
    -webkit-transform: translateY(-5px);
  }
}
@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}
.bounce {
  -webkit-animation-name: bounce;
  animation-name: bounce;
}
#animated-example {
  width: 20px;
  height: 20px;
  background-color: red;
  position: relative;
  top: 100px;
  left: 100px;
  border-radius: 50%;
}
hr {
  position: relative;
  top: 92px;
  left: -300px;
  width: 200px;
}
<div id="animated-example" class="animated bounce"></div>
<hr>

以下是浏览器解释您的原始keyframe设置的方式:

在0%(即在0%或动画开始时)-translate在Y轴上为0px。 在20%(即动画的0.5s)-translate在Y轴上为0px。 在40%(即动画的1s)-translate在Y轴上为0px。 50%(即动画的1.25s)-在Y轴上translate5px。这会导致逐渐向上移动。 在60%(即动画的1.5s)-translate在Y轴上为0px。这会导致逐渐向下移动。 在80%(即在动画的2秒处)-translate在Y轴上为0px。 在100%(即在2.5s或动画结束时)-translate在Y轴上乘以0px。

796