jquery – 重新启动动画GIF作为背景图像

是否可以重新启动用作背景图像的动画GIF?

考虑这个HTML:

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

而这种风格:

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

我想要blink.gif动画播放每次我添加类闪烁#eyes,而不仅仅是第一次。

我期望这样工作:

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

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

问题是Firefox和WebKit浏览器一旦播放一次,就不会再播放背景图像GIF动画。添加/删除类闪烁仅在第一次工作。

解决方法

您可以通过重新加载动画gif来重播。这不是理想的带宽,特别是如果您的图像很大,但会强制重新启动动画。

在我的例子中,我将添加删除它< div id =“animated”&gt ;:

$('#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在行动。

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...