在悬停时播放CSS动画,在悬停时暂停

时间:2012-01-12 21:13:24

标签: css animation hover

我正在尝试

  • 悬停时播放动画。
  • 悬停时暂停动画(即不要回到第0帧)。

是否无法在父div上使用-webkit-animation-play-state: paused;

查看example here,当您将鼠标悬停时,会返回第0帧。

我不想使用JS。

4 个答案:

答案 0 :(得分:11)

example jsfiddle

在播放状态暂停的#tech上设置动画

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

然后将播放状态更改为在悬停时运行

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

答案 1 :(得分:3)

我也在寻找这个,@MikeM的答案让我得到了我需要去的地方,并且@HellGate对Chrome的答案发表了评论:

  

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

我感兴趣的是如何在PNG精灵表不活动时暂停动画,并在悬停时继续/恢复,所以接受的答案在这方面有所帮助。

这是一个演示,展示了如何在PNG精灵表上完成此操作(奖励精灵,原始CSS转到Guil Hernandez及其精彩的博文here):CodePen。< / p>

重要的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; }
}

答案 2 :(得分:0)

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

动画不会停止,因为animation的后期定义会覆盖属性animation-play-state的值。根据{{​​3}},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-stateW3C specification):

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

或者你可以简单地使用(http://jsfiddle.net/fRzwS/373/):

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

以下是另一个适用于Chrome和Firefox的示例:http://jsfiddle.net/fRzwS/374/

答案 3 :(得分:0)

我没有足够的声誉评论其他答案。好。 @MikeM的方式有效,但他犯了一点错误。看:

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

这不起作用,这不起作用。动画速记备注覆盖animation-play-state。您需要重新排序这些字符串才能使其正常工作

相关问题