在悬停时播放CSS动画,鼠标移开时暂停

10

我想实现以下功能:

  • 鼠标悬停时播放动画。
  • 鼠标移开时暂停动画(即不返回第0帧)。

在父级div上使用-webkit-animation-play-state: paused;不可行吗?

请参考此示例,当你将鼠标移开时,它会返回到第0帧。

我不想使用 JS。

4个回答

13

使用paused play状态,对#tech设置动画

jsfiddle示例

#tech {
    -webkit-animation-play-state:paused;
    -webkit-animation: moveSlideshow 10s linear infinite;
}

当鼠标悬停时,将播放状态更改为运行

#tech:hover{
    -webkit-animation-play-state:running;
}

谢谢,我简直不敢相信我错过了这一点,roXon你需要为 Firefox 加上 -moz 前缀。 - Neo
我知道...只是在演示中更改它。(编辑上面的评论) - Roko C. Buljan
8
在Chrome浏览器下它无法运行。图片一直在移动。 - Krasimir
1
你需要在动画后加上暂停状态,否则它将无法正常工作。 - HellGate

3
我也在寻找这个答案,@MikeM的回答让我找到了需要的内容,而@HellGate在该回答中提到了Chrome:

你需要在动画后暂停状态,否则它不起作用。

我对如何在PNG精灵表上暂停动画当它处于非活动状态时并在悬停时继续/恢复感兴趣,所以被接受的答案对此有所帮助。
这是一个演示,展示了如何在PNG精灵表上实现此操作(对于精灵和原始CSS,感谢Guil Hernandez和他出色的博客文章这里):CodePen
重要的CSS部分:
.monster {
  width: 190px;
  height: 240px;
  margin: 2% auto;
  background: url('http://treehouse-code-samples.s3.amazonaws.com/CSS-DD/codepen/blog/monster.png') left center;
  -webkit-animation: monsterAnimation .8s steps(10) infinite;
  animation: monsterAnimation .8s steps(10) infinite;
  -webkit-animation-play-state: paused;  /* Chrome, Safari, Opera */
  animation-play-state: paused;
}

.monster:hover {
  -webkit-animation-play-state: running;
  animation-play-state: running;
}

@keyframes monsterAnimation {
  100% { background-position: -1900px; }
}

0

在这里检查JSFiddle:http://jsfiddle.net/fRzwS/373/

动画不停止是因为animation的后期定义覆盖了属性animation-play-state的值。根据W3C规范animation

The 'animation' shorthand property is a comma-separated list of 
  animation definitions, each of which combines seven of 
  the animation properties into a single component value.

而这七个属性是:

<single-animation> = <single-animation-name> || <time> 
  || <single-animation-timing-function> 
  || <time> || <single-animation-iteration-count> || <single-animation-direction> 
  || <single-animation-fill-mode> || <single-animation-play-state>

这与属性 backgroundbackground-color 类似。

因此,在原始代码中:

#tech {
    -webkit-animation-play-state: paused;
    -webkit-animation: moveSlideshow 10s linear infinite;
}

属性animation-play-state被设置为paused。然而,后面的属性animation通过其默认值running覆盖了这个值。所以,你可以稍后定义属性animation-play-statehttp://jsfiddle.net/fRzwS/373/):
#tech {
    -webkit-animation: moveSlideshow 10s linear infinite;
    -webkit-animation-play-state:paused;
}

或者你可以直接使用(http://jsfiddle.net/fRzwS/374/):

-webkit-animation: moveSlideshow 10s linear infinite paused;

以下是一个在Chrome和Firefox都可用的示例: http://jsfiddle.net/MaY5A/694/


0

我没有足够的声望来评论其他答案。嗯,@MikeM的方法是可行的,但他犯了一个小错误。看:

#tech {
    -webkit-animation-play-state:paused;
    -webkit-animation: moveSlideshow 10s linear infinite;
}

这个不起作用,也不应该起作用。动画缩写覆盖了animation-play-state。你需要重新排列这些字符串才能让它工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接