有没有一种方法可以让GIF在鼠标悬停时播放并暂停?

时间:2019-08-14 00:16:27

标签: html css hover gif playback

我想知道是否有一种方法可以使GIF具有这种确切的行为:

  • 页面开始暂停;
  • 仅在悬停时播放;
  • 在将鼠标拖出图像时的确切帧处暂停。

是否可以这样做?最好不要使用JavaScript,但如有必要,我可以使用它。

1 个答案:

答案 0 :(得分:2)

有。基本上,您将需要使用单个框架自己创建gif。本质上,您创建X帧,然后使用keyframes作为绝对定位的div的background-image属性浏览它们。 “ gif”以属性animation-play-state:paused开头,并在悬停时更改为running。可以明显地切换这些属性。请考虑以下内容:

您的标记:

<div class="gif"></div>

以及您的CSS:

.gif {
    position: absolute;
    margin: auto;
    background-image: url(/path/to/starting.frame);
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
    animation: play 0.5s infinite steps(1);
    animation-play-state: paused;
}
.gif:hover {
    animation-play-state:running;
}

@keyframes play {
    0%   { background-image: url('/path/to/0.frame'); } 
    15%  { background-image: url('/path/to/1.frame'); }
    30%  { background-image: url('/path/to/2.frame'); }
    45%  { background-image: url('/path/to/3.frame'); }
    60%  { background-image: url('/path/to/4.frame'); }
    75%  { background-image: url('/path/to/5.frame'); }
    90%  { background-image: url('/path/to/6.frame'); }
    100% { background-image: url('/path/to/7.frame'); }
}

Here is an example我能够找到和更改。