小编典典

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

css

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

考虑以下HTML:

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

而这种风格:

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

我想在blink.gif动画播放每次我的类添加时间blink#eyes,不只是第一次。

我希望这可以工作:

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

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

问题在于,一旦Firefox和WebKit浏览器播放一次,它们就不会再次播放背景图像GIF动画。添加/删除班级眨眼仅在第一次时有效。


阅读 624

收藏
2020-05-16

共1个答案

小编典典

您可以通过重新加载动画来重播gif。这对于带宽来说并不是理想的选择,尤其是在您的图像较大的情况下,但这会强制重新启动动画。

在我的例子,我添加和删除它onclick<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"});
    }
})
2020-05-16