【问题标题】:Is there a way to make GIF play on hover and pause when mouse is out?有没有办法让 GIF 在鼠标悬停时播放并暂停?
【发布时间】:2019-12-20 12:58:46
【问题描述】:

我想知道是否有办法让 GIF 具有这种确切的行为:

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

可以这样做吗?最好不用 JavaScript,但如果需要我可以使用它。

【问题讨论】:

    标签: html css hover gif playback


    【解决方案1】:

    有。基本上,您需要使用单独的帧自己创建 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我能够找到并更改。

    【讨论】:

    • 谢谢。我在等待答案时弄乱了代码并发现了这种方法,但是在 GIF 的第一个循环中,它每帧都闪烁。为什么会这样?
    • @Prinzherbert 因为每个帧都在关键帧旋转期间加载到 DOM 中。您可以通过预加载图像来解决此问题。
    • 哦,我明白了。我实际上想做其中的 11 个,那么有没有办法让它更紧凑?
    • @Prinzherbert 是的,您可以根据需要制作任意数量的内容。只需计算 100 除以您的最终帧数,然后使您的百分比相差那么远。例如,如果您有 21 帧,则 100/20 = 5(因为第一帧为 0%),您的关键帧百分比将为 0、5、10、15、20、25 等,每个都有对应的该帧的图像。
    • 我不是那个意思。我为我的 GIF 制作了 20 帧,但我想要这 20 帧 GIF 中的 11 帧。考虑到预加载行,大概是 440 行,所以我想知道是否有任何方法可以以更紧凑的方式达到相同的效果。
    猜你喜欢
    • 2018-07-31
    • 2015-09-16
    • 2014-01-05
    • 1970-01-01
    • 2012-01-21
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多