我想实现以下功能:
- 鼠标悬停时播放动画。
- 鼠标移开时暂停动画(即不返回第0帧)。
在父级div上使用-webkit-animation-play-state: paused;
不可行吗?
请参考此示例,当你将鼠标移开时,它会返回到第0帧。
我不想使用 JS。
使用paused play状态,对#tech
设置动画
#tech {
-webkit-animation-play-state:paused;
-webkit-animation: moveSlideshow 10s linear infinite;
}
当鼠标悬停时,将播放状态更改为运行
#tech:hover{
-webkit-animation-play-state:running;
}
我对如何在PNG精灵表上暂停动画当它处于非活动状态时并在悬停时继续/恢复感兴趣,所以被接受的答案对此有所帮助。你需要在动画后暂停状态,否则它不起作用。
.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; }
}
在这里检查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>
这与属性 background
和 background-color
类似。
因此,在原始代码中:
#tech {
-webkit-animation-play-state: paused;
-webkit-animation: moveSlideshow 10s linear infinite;
}
animation-play-state
被设置为paused
。然而,后面的属性animation
通过其默认值running
覆盖了这个值。所以,你可以稍后定义属性animation-play-state
(http://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/
我没有足够的声望来评论其他答案。嗯,@MikeM的方法是可行的,但他犯了一个小错误。看:
#tech {
-webkit-animation-play-state:paused;
-webkit-animation: moveSlideshow 10s linear infinite;
}
这个不起作用,也不应该起作用。动画缩写覆盖了animation-play-state
。你需要重新排列这些字符串才能让它工作。