Onclick play GIF image with jQuery and start from beginning

这一生的挚爱 提交于 2019-12-19 03:59:40

问题


I have a website with images on it. Some of the images are animated GIF images. What I've done is to show a static image of the GIF and on a click event, the actual GIF images is displayed.

Here is my code:

JQuery

$(".theimage").click(function() {
$(this).addClass('hidden');
$(this).next().removeClass('hidden');
});
$(".theimage2").click(function() {
 $(this).addClass('hidden');
$(this).prev().removeClass('hidden');
});

HTML

<img class="theimage" src="image_static.gif" alt=""/>

<img class="theimage2 hidden" src="image_animated.gif" alt=""/>

CSS

.hidden{
display:none !important;
}

I am changing the class of the previous and next elements because I may have more than one GIF image on a single page, thus preventing the action of occurring for all of them.

So far so good, the script works. What I am trying to achieve actually is for the GIF image to always start from the beginning. At the moment it only does so the first time. Then, it looks like it continues playing in the background and on the second call, it simply continues playing. Sometimes even it freezes, something to do with cache I guess.

How can i accomplish this?


回答1:


this would be a solution to larger images Restart an animated GIF from JavaScript without reloading the image

in a nut shell load the image into a javascript variable then change out the src on click

$(function(){
    var image = new Image();
       image.src='http://rack.3.mshcdn.com/media/ZgkyMDEyLzEwLzE5LzExXzMzXzMzXzE3Nl9maWxlCnAJdGh1bWIJMTIwMHg    5NjAwPg/462b8072';
     $('#img').click(function(){
       $(this).attr('src',image.src);
     }); 
 });

http://jsfiddle.net/GS427/1/

its ugly i couldnt find the right image for the starting but you can see that it starts in the same place every time




回答2:


You need to divide mouse event to mousedown and mouseup, perform hiding first and showing second or viceversa on mousedown then perform hiding first and showing second or viceversa on up,



来源:https://stackoverflow.com/questions/20249401/onclick-play-gif-image-with-jquery-and-start-from-beginning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!