重新启动动画 GIF 作为背景图像 [英] Restart animated GIF as background-image

查看:43
本文介绍了重新启动动画 GIF 作为背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以重新启动用作 background-image 的动画 GIF?

考虑这个 HTML:

<div id="眼睛"></eyes>

还有这种风格:

#eyes.blink {背景图片:网址('blink.gif');}

我希望每次将 blink 类添加到 #eyes 时播放 blink.gif 动画,而不仅仅是第一次.

我希望这能奏效:

function startBlink() {$('#eyes').addClass('blink');}函数 stopBlink() {$('#eyes').removeClass('blink');}

问题是 Firefox 和 WebKit 浏览器在播放一次背景图像 GIF 动画后都不会再次播放.添加/删除类闪烁仅在第一次有效.

解决方案

您可以通过重新加载动画 gif 来重播它.这对于带宽来说并不理想,尤其是当您的图像很大时,但它会强制重新启动动画.

在我的示例中,我添加和删除了

onclick:

$('#animated').click(function() {/* 引用被点击的元素并切换 .go 类 */var $div = $(this);$div.toggleClass('go');/* 开始动画 gif */如果 ($div.hasClass('go')) {/* 创建一个 元素并将其作为 src 的动画 gif.到强制重新加载我们在 URL 中添加一个日期参数 */var img = document.createElement('img');img.src = "http://yoursite.com/animated.gif?p" + new Date().getTime();/* 加载图像后,将其设置为背景图像 */$(img).load(function(){$div.css({backgroundImage: "url("+img.src+")"});});/* 删除背景图片 */} 别的 {$div.css({backgroundImage: "none"});}})

演示在行动中.

Is it possible to restart an animated GIF used as background-image?

Consider this HTML:

<div id="face">
    <div id="eyes"></eyes>
</div>

And this style:

#eyes.blink {
    background-image:url('blink.gif');
}

I would like the blink.gif animation to play every time I add the class blink to #eyes, not just the first time.

I expected this to work:

function startBlink() {
    $('#eyes').addClass('blink');
}

function stopBlink() {
    $('#eyes').removeClass('blink');
}

The problem is that both Firefox and WebKit browser do not play a background-image GIF animation again once it has played once. Adding/removing the class blink only works the first time.

解决方案

You can get the animated gif to replay by reloading it. This isn't ideal for bandwidth, especially if your image is large, but it will force a restart of the animation.

In my example I'm adding and removing it onclick of <div id="animated">:

$('#animated').click(function() {

    /* Reference to the clicked element and toggle the .go class */
    var $div = $(this);
    $div.toggleClass('go');

    /* Start the animated gif */
    if ($div.hasClass('go')) {

        /* Create an <img> element and give it the animated gif as a src.  To 
           force a reload we add a date parameter to the URL */
        var img = document.createElement('img');
        img.src = "http://yoursite.com/animated.gif?p" + new Date().getTime();

        /* Once the image has loaded, set it as the background-image */
        $(img).load(function(){
            $div.css({backgroundImage: "url("+img.src+")"});
        });

    /* Remove the background-image */        
    } else {
       $div.css({backgroundImage: "none"});
    }
})

Demo of it in action.

这篇关于重新启动动画 GIF 作为背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆