How to play a GIF on click (like 9GaG.com) with wordpress?

前端 未结 2 1317
梦毁少年i
梦毁少年i 2021-02-08 09:08

I need to implement this \"gif player\" in a wordpress site, because gif pages are up to 6mb, so performance is really crappy

I´ve read this Onclick play GIF image with

相关标签:
2条回答
  • 2021-02-08 09:58

    What 9GAG essentially did was it had two images - one was the animated GIF, and the other was a still JPG.

    Before you clicked on it, it showed the JPG file. After you clicked on it, it loaded the GIF into the same <img> tag, and made you think it "played" the GIF image.

    If you click on it again, it loads the JPG file back into the <img> tag, and made you think it "paused" the GIF image.

    Image manipulation, like only using one GIF and pausing and playing it is far, far too difficult to be of practical use - this method is one of the better ways to do it.

    Here's some code:

    <div id="gifdiv">
      <img src="staticgif.jpg" />
    </div>
    <script type="text/javascript">
      $("#gifdiv").click(function () {
        if ($(this).find("img").attr("data-state") == "static") {
          $(this).find("img").attr("src", "animatedgif.gif");
        } else {
          $(this).find("img").attr("src", "staticgif.jpg");
        }
      });
    </script>
    

    Also, if you wish for speed, I think 9GAG does it by preloading the GIF beforehand, like this:

    <script type="text/javascript">
      (new Image()).src = "animatedgif.gif"; // this would preload the GIF, so future loads will be instantaneous
    </script>
    

    Hope this helps.

    0 讨论(0)
  • 2021-02-08 10:01

    If you don't want to pause, you can easily REPLAY the gif file. Just trigger on the click and reload the gif into the image tag.

    your_image= document.getElementById or however you want to grab the reference to the image. then set an event listener for the click.

    Then your_image.src= your_image.src; And the gif will run again.

    0 讨论(0)
提交回复
热议问题