如何在悬停和按时摇动图像

时间:2018-05-30 09:26:04

标签: css css3 css-animations

我想在用户位于图像上方(悬停效果)时每5秒钟抖动一次图像。我的代码:



.opona:hover {
  animation: shake 0.82s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

/*
.opona {
  -webkit-animation-name: shake;
  -webkit-animation-duration: 5s;
  -webkit-animation-delay: 0.82s;
}
*/

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

<div class="opona">
  <img src="https://www.firestonetire.com/content/dam/bridgestone/consumer/fst/tire-images/Firehawk%20AS/FST_Firehawk_AS.jpg/_jcr_content/renditions/original" alt="" width="50px">
</div>
&#13;
&#13;
&#13;

当我从.opona删除评论时,效果不起作用。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

在这种情况下,您希望animation持续10.82s,其中“移动”部分只需 0.82s ,因此留下 10s 间隙。为了做到这一点,您只需要使用已定义的@keyframes %进行一些调整。

0.82 / 10.82 = ~7.6%,即“移动”部分仅占用动画的 7.6% - 持续时间

所以要更新%只需将当前乘以0.076:

.opona:hover {
  animation: shake 10.82s cubic-bezier(.36, .07, .19, .97) both infinite;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  .76%, 6.84% {transform: translate3d(-1px, 0, 0)}
  1.52%, 6.08% {transform: translate3d(2px, 0, 0)}
  2.28%, 3.8%, 5.32% {transform: translate3d(-4px, 0, 0)}
  3.04%, 4.56% {transform: translate3d(4px, 0, 0)}
}
<div class="opona">
  <img src="https://www.firestonetire.com/content/dam/bridgestone/consumer/fst/tire-images/Firehawk%20AS/FST_Firehawk_AS.jpg/_jcr_content/renditions/original" alt="" width="50px">
</div>