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

后端 未结 11 1596
暗喜
暗喜 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:44

    I came across this thread after searching many others. David Bell's post led me to the solution I needed.

    I thought I'd post my experience in the event that it could be useful for anyone trying to accomplish what I was after. This is for an HTML5/JavaScript/jQuery web app that will be an iPhone app via PhoneGap. Testing in Chrome.

    The Goal:

    1. When user taps/clicks button A, an animated gif appears and plays.
    2. When user taps/clicks button B, gif disappears.
    3. When user taps/clicks button A again, after tapping/clicking button B, animated gif should reappear and play from the beginning.

    The Problem:

    • On tap/click of button A, I was appending the gif to an existing div. It would play fine.
    • Then, on tap/click of button B, I was hiding the container div, then setting the img src of the gif to an empty string (''). Again, no problem (that is, the problem wasn't evident yet.)
    • Then, on tap/click of button A, after tap/click of button B, I was re-adding the path to the gif as the src.

      - This did not work. The gif would show up on subsequent taps/clicks of button A...however, the more I tapped/clicked button A, the more times the gif would load and start over. That is, if I went back and forth, tapping/clicking button A then button B 3 times, the gif would appear and then start/stop/start 3 times...and my whole app started to chug. I guess the gif was being loaded multiple times, even though I had set the src to an empty string when button B was tapped/clicked.

    The Solution:

    After looking at David Bell's post, I arrived at my answer.

    1. I defined a global variable (let's call it myVar) that held the container div and the image (with the source path) within.
    2. On the tap/click function of button A, I appended that container div to an existing parent div in the dom.
    3. In that function, I created a new variable that holds the src path of the gif.

    Just like David suggested, I did this (plus an append):

    $('#mainParent').append(myVar);
    var imgsrc = $('#my_image').attr('src');
    $('#my_image').attr('src', '');
    $('#my_image').attr('src', imgsrc);
    

    THEN, in the function for button B, I set the src to an empty string and then removed the div containing the gif:

    $('#my_image').attr('src', '');
    $('#mainParent').find('#my_image').remove();
    

    Now, I can tap/click button A then button B then button A, etc., all day long. The gif loads and plays on tap/click of button A, then hides on tap/click of button B, then loads and plays from the beginning on subsequent taps of button A every time with no issues.

提交回复
热议问题