Proper way to reset a GIF animation with display:none on Chrome

后端 未结 11 1512
暗喜
暗喜 2020-12-03 05:21

Title is self-explanatory, but I\'ll provide a step-by-step view on the matter. Hopefully I\'m not the first one to have noticed this (apparently) bug on Webkit/Chrome.

相关标签:
11条回答
  • 2020-12-03 05:48

    The most reliable way to "reset" a GIF is by appending a random query string. However this does mean that the GIF will be redownloaded every time so make sure it's a small file.

    // reset a gif:
    img.src = img.src.replace(/\?.*$/,"")+"?x="+Math.random();
    
    0 讨论(0)
  • 2020-12-03 05:48

    I experienced problems with all of the above solutions. What finally worked was replacing the src temporarily with a transparent 1px gif:

    var transparent1PxGif = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
    var reloadGif = function(img) {
        var src = img.src;
        img.src = transparent1PxGif;
        img.offsetHeight; // triggers browser redraw
        img.src = src;
    };
    
    0 讨论(0)
  • 2020-12-03 05:50

    I've a button with the an animated no-loop image in it. I just reload the image with some jquery and this seems to be working for me.

    var asdf = $(".settings-button img").attr("src");
    $(".settings-button img").attr("src", "").attr("src", asdf);
    
    0 讨论(0)
  • 2020-12-03 05:51

    Just because I still need this every now and then I figured the pure JS function I use might be helpful for someone else. This is a pure JS way of restarting an animated gif, without reloading it. You can call this from a link and/or document load event.

    <img id="img3" src="../_Images/animated.gif">
    
    <a onClick="resetGif('img3')">reset gif3</a>
    
    <script type="text/javascript">
    
    // reset an animated gif to start at first image without reloading it from server.
    // Note: if you have the same image on the page more than ones, they all reset.
    function resetGif(id) {
        var img = document.getElementById(id);
        var imageUrl = img.src;
        img.src = "";
        img.src = imageUrl;
    };
    
    </script>
    

    On some browsers you only need to reset the img.src to itself and it works fine. On IE you need to clear it before resetting it. This resetGif() picks the image name from the image id. This is handy in case you ever change the actual image link for a given id because you do not have to remember to change the resetGiF() calls.

    --Nico

    0 讨论(0)
  • 2020-12-03 05:51

    This seemed to work for me in Chrome, it runs each time just before I fade in the image and clears then refills the src and my animation now starts from the beginning every time.

    var imgsrc = $('#my_image').attr('src');
    $('#my_image').attr('src', '');
    $('#my_image').attr('src', imgsrc);
    
    0 讨论(0)
提交回复
热议问题