如何在页面加载时启动CSS动画,并使用鼠标悬停在同一元素上触发相同的动画。在页面加载时,动画将迭代1次。一旦停止,我将能够通过悬停反复触发它。我尝试在different CSS animation on load and on hover处重新编写代码,但无法复制它。我还拼凑了以下内容,但只有载入动画有效,而悬停却没有:

img {
    -webkit-animation: anim 10s linear;
    -webkit-animation-iteration-count: 1;
    animation: anim 10s linear;
    animation-iteration-count: 1;
    height: 50px;
    width: 50px;
}

img:hover {
    -webkit-animation: anim 10s infinite linear ;
    animation: anim 10s infinite linear;
    height: 50px;
    width: 50px;
}

@-webkit-keyframes anim {
    from { -webkit-transform: rotateX(0deg); }
    to { -webkit-transform: rotateX(360deg); }
}

@keyframes anim {
    from { transform: rotateX(0deg); }
    to { transform: rotateX(360deg); }
}


根据维托里诺·费尔南德斯(Vitorino Fernandes)关于使用父div进行悬停的建议,我开始使用它:

img {
    -webkit-animation: anim 10s linear;
    -webkit-animation-iteration-count: 1;
    animation: anim 10s linear;
    animation-iteration-count: 1;

    height: 50px;
    width: 50px;
}

div:hover {
    -webkit-animation: anim 10s infinite linear;
    animation: anim 10s infinite linear;
    height: 50px;
    width: 50px;
}

@-webkit-keyframes anim {
    from { -webkit-transform: rotateX(0deg); }
    to { -webkit-transform: rotateX(360deg); }
}

@keyframes anim {
    from { transform: rotateX(0deg); }
    to { transform: rotateX(360deg); }
}


HTML:

<div>
    <img src="testpic.jpg"/>
</div>

最佳答案

您可以为父项添加悬停事件,为img添加加载事件



img {
  -webkit-animation: anim 10s linear;
  -webkit-animation-iteration-count: 1;
  animation: anim 10s linear;
  animation-iteration-count: 1;
  height: 50px;
  width: 50px;
}
div:hover {
  display: inline-block;
  -webkit-animation: anim 10s infinite linear;
  -webkit-animation-iteration-count: 1;
  animation: anim 10s linear;
  animation-iteration-count: 1;
  height: 50px;
  width: 50px;
}
@-webkit-keyframes anim {
  0%, 100% {
    -webkit-transform: rotateX(0deg);
  }
  50% {
    -webkit-transform: rotateX(360deg);
  }
}

<div>
  <img src="http://placehold.it/350x150" />
</div>

10-05 20:57
查看更多