Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

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

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.

I want to reset a GIF animation. All of the examples I've seen so far either simply set the src of the image to itself or set it to an empty string followed by the original src again.

Take a look at this JSFiddle for reference. The GIF resets perfectly fine on IE, Firefox and Chrome.

The issue which I have is when the image has display:none on Google Chrome only.

Check this JSFiddle. The GIF resets fine on IE and Firefox before being displayed in the page, but Chrome simply refuses to reset its animation!

What I've tried so far:

  • Setting the src to itself as in Fiddle, doesn't work in Chrome.
  • Setting the src to an empty string and restoring it to the default, doesn't work either.
  • Putting an wrapper around the image, emptying the container through .html('') and putting the image back inside of it, doesn't work either.
  • Changing the display of the image through .show() or .fadeIn() right before setting the src doesn't work either.

The only workaround which I've found so far is keeping the image with its default display and manipulating it through .animate()ing and .css()ing the opacity, height and visibility when necessary to simulate a display:none behaviour.

The main reason (context) of this question is that I wanted to reset an ajax loader GIF right before fading it in the page.

So my question is, is there a proper way to reset a GIF image's animation (which avoids Chrome's display:none "bug") or is it actually a bug?

(ps. You may change the GIF in the fiddles for a more appropriate/longer animation gif for testing)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...