微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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在行动。

原文地址:https://www.jb51.cc/jquery/181907.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐