jQuery 停止加载 gif 动画,鼠标悬停时开始激活

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5818003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:51:48  来源:igfitidea点击:

Stop a gif animation onload, on mouseover start the activation

jquerygif

提问by denislexic

I have a page with a lot of GIFs.

我有一个包含很多 GIF 的页面。

<img src="gif/1303552574110.1.gif" alt="" >
<img src="gif/1302919192204.gif" alt="" >
<img src="gif/1303642234740.gif" alt="" >
<img src="gif/1303822879528.gif" alt="" >
<img src="gif/1303825584512.gif" alt="" >

What I'm looking for

我在找什么

1 On page load => Animations for all gifs are stopped

1 在页面加载 => 停止所有 gif 的动画

2 On mouseover => Animations starts for that one gif

2 鼠标悬停 => 动画开始为那个 gif

3 On mouseout => Animation stops again for that gif

3 在 mouseout => 动画再次停止该 gif

I suppose this can be done in Jquery but I don't know how.

我想这可以在 Jquery 中完成,但我不知道如何。

回答by Guffa

No, you can't control the animation of the images.

不,您无法控制图像的动画。

You would need two versions of each image, one that is animated, and one that's not. On hover you can easily change from one image to another.

您需要每个图像的两个版本,一个是动画的,一个不是。在悬停时,您可以轻松地从一个图像更改为另一个图像。

Example:

例子:

$(function(){
  $('img').each(function(e){
    var src = $(e).attr('src');
    $(e).hover(function(){
      $(this).attr('src', src.replace('.gif', '_anim.gif'));
    }, function(){
      $(this).attr('src', src);
    });
  });
});

Update:

更新:

Time goes by, and possibilities change. As kritzikatzi pointed out, having two versions of the image is not the only option, you can apparently use a canvas element to create a copy of the first frame of the animation. Note that this doesn't work in all browsers, IE 8 for example doesn't support the canvas element.

时间在流逝,可能性在变化。正如 kritzikatzi 指出的那样,拥有两个版本的图像并不是唯一的选择,显然您可以使用画布元素来创建动画第一帧的副本。请注意,这不适用于所有浏览器,例如 IE 8 不支持 canvas 元素。

回答by Mark Kramer

I realise this answer is late, but I found a rather simple, elegant, and effective solution to this problem and felt it necessary to post it here.

我意识到这个答案来晚了,但我找到了一个相当简单、优雅和有效的解决方案,并觉得有必要在这里发布它。

However one thing I feel I need to make clear is that this doesn't start gif animation on mouseover, pause it on mouseout, and continue it when you mouseover it again. That, unfortunately, is impossible to do with gifs. (It is possible to do with a string of images displayed one after another to look like a gif, but taking apart every frame of your gifs and copying all those urls into a script would be time consuming)

然而,我觉得我需要澄清的一件事是,这不会在鼠标悬停时启动 gif 动画,在鼠标悬停时暂停它,并在您再次将鼠标悬停时继续它。不幸的是,这对 gif 来说是不可能的。(可以将一串图像一个接一个地显示,使其看起来像 gif,但是将 gif 的每一帧都拆开并将所有这些 url 复制到脚本中会很耗时)

What my solution does is make an image looks like it starts moving on mouseover. You make the first frame of your gif an image and put that image on the webpage then replace the image with the gif on mouseover and it looks like it starts moving. It resets on mouseout.

我的解决方案所做的是使图像看起来好像在鼠标悬停时开始移动。您将 gif 的第一帧设为图像并将该图像放在网页上,然后在鼠标悬停时用 gif 替换图像,看起来它开始移动了。它在鼠标退出时重置。

Just insert this script in the head section of your HTML:

只需在 HTML 的 head 部分插入此脚本:

$(document).ready(function()
{
    $("#imgAnimate").hover(
        function()
        {
            $(this).attr("src", "GIF URL HERE");
        },
        function()
        {
            $(this).attr("src", "STATIC IMAGE URL HERE");
        });
});

And put this code in the img tag of the image you want to animate.

并将此代码放在要设置动画的图像的 img 标签中。

id="imgAnimate"

This will load the gif on mouseover, so it will seem like your image starts moving. (This is better than loading the gif onload because then the transition from static image to gif is choppy because the gif will start on a random frame)

这将在鼠标悬停时加载 gif,因此您的图像似乎开始移动。(这比在加载时加载 gif 更好,因为这样从静态图像到 gif 的过渡会断断续续,因为 gif 将在随机帧上开始)

for more than one image just recreate the scriptcreate a function:

对于多个图像,只需重新创建脚本创建一个函数:

<script type="text/javascript">

var staticGifSuffix = "-static.gif";
var gifSuffix = ".gif";

$(document).ready(function() {

  $(".img-animate").each(function () {

     $(this).hover(
        function()
        {
            var originalSrc = $(this).attr("src");
            $(this).attr("src", originalSrc.replace(staticGifSuffix, gifSuffix));
        },
        function()
        {
            var originalSrc = $(this).attr("src");
            $(this).attr("src", originalSrc.replace(gifSuffix, staticGifSuffix));  
        }
     );

  });

});
</script>

</head>
<body>

<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >

</body>

That code block is a functioning web page (based on the information you have given me) that will display the static images and on hover, load and display the gif's. All you have to do is insert the url's for the static images.

该代码块是一个功能正常的网页(基于您提供给我的信息),它将显示静态图像并在悬停时加载和显示 gif。您所要做的就是插入静态图像的 url。

回答by Hirvesh

I think the jQuery plugin freezeframe.jsmight come in handy for you. freezeframe.js is a jQuery Plugin To Automatically Pause GIFs And Restart Animating On Mouse Hover.

我认为jQuery 插件 freezeframe.js可能对你有用。freezeframe.js 是一个 jQuery 插件,用于自动暂停 GIF 并在鼠标悬停时重新启动动画。

I guess you can easily adapt it to make it work on page load instead.

我想您可以轻松地调整它以使其在页面加载时工作。

回答by Nick Brunt

The best option is probably to have a still image which you replace the gif with when you want to stop it.

最好的选择可能是有一个静止图像,当你想停止它时,你可以用它替换 gif。

<img src="gif/1303552574110.1.gif" alt="" class="anim" >
<img src="gif/1302919192204.gif" alt="" class="anim" >
<img src="gif/1303642234740.gif" alt="" class="anim" >
<img src="gif/1303822879528.gif" alt="" class="anim" >
<img src="gif/1303825584512.gif" alt="" class="anim" >

$(window).load(function() {
  $(".anim").src("stillimage.gif");
});

$(".anim").mouseover(function {
  $(this).src("animatedimage.gif");
});

$(".anim").mouseout(function {
  $(this).src("stillimage.gif");
});

You probably want to have two arrays containing paths to the still and animated gifs which you can assign to each image.

您可能希望有两个包含静态和动画 gif 路径的数组,您可以将它们分配给每个图像。

回答by Xananax

You can solve this by having a long stripe that you show in steps, like a filmstrip. Then you can stop the film on any frame. Example below (fiddle available at http://jsfiddle.net/HPXq4/9/):

您可以通过逐步显示长条纹来解决此问题,例如幻灯片。然后您可以在任何帧上停止电影。下面的示例(小提琴可在http://jsfiddle.net/HPXq4/9/ 获得):

the markup:

标记:

 <div class="thumbnail-wrapper">
     <img src="blah.jpg">
 </div>

the css:

css:

.thumbnail-wrapper{
   width:190px;
   height:100px;
   overflow:hidden;
   position:absolute;
}
.thumbnail-wrapper img{
   position:relative;
   top:0;
}

the js:

js:

var gifTimer;
var currentGifId=null;
var step = 100; //height of a thumbnail
$('.thumbnail-wrapper img').hover(
   function(){
      currentGifId = $(this)
      gifTimer = setInterval(playGif,500);
   },
   function(){
       clearInterval(gifTimer);
       currentGifId=null;
   }
);

var playGif = function(){
   var top = parseInt(currentGifId.css('top'))-step;
   var max = currentGifId.height();
   console.log(top,max)
   if(max+top<=0){
     console.log('reset')
     top=0;
   }
   currentGifId.css('top',top);
}

obviously, this can be optimized much further, but I simplified this example for readability

显然,这可以进一步优化,但为了可读性我简化了这个例子

回答by Антон Баранов

For restarting the animation of a gif image, you can use the code:

要重新启动 gif 图像的动画,您可以使用以下代码:

$('#img_gif').attr('src','file.gif?' + Math.random());

回答by Finn Fitzsimons

A more elegant version of Mark Kramer's would be to do the following:

Mark Kramer 的更优雅版本是执行以下操作:

function animateImg(id, gifSrc){
  var $el = $(id),
    staticSrc = $el.attr('src');
  $el.hover(
    function(){
      $(this).attr("src", gifSrc);
    },
    function(){
      $(this).attr("src", staticSrc);
    });
}

$(document).ready(function(){
  animateImg('#id1', 'gif/gif1.gif');
  animateImg('#id2', 'gif/gif2.gif');
});

Or even better would be to use data attributes:

或者更好的是使用数据属性:

$(document).ready(function(){
  $('.animated-img').each(function(){
    var $el = $(this),
      staticSrc = $el.attr('src'),
      gifSrc = $el.data('gifSrc');
    $el.hover(
      function(){
        $(this).attr("src", gifSrc);
      },
      function(){
        $(this).attr("src", staticSrc);
      });
  });
});

And the img el would look something like:

img el 看起来像:

<img class="animated-img" src=".../img.jpg" data-gif-src=".../gif.gif" />

Note: This code is untested but should work fine.

注意:此代码未经测试,但应该可以正常工作。

回答by Leonardo Gugliotti

Adding a suffix like this:

添加这样的后缀:

$('#img_gif').attr('src','file.gif?' + Math.random());  

the browser is compelled to download a new image every time the user accesses the page. Moreover the client cache may be quickly filled.

每次用户访问页面时,浏览器都被迫下载新图像。此外,客户端缓存可能会很快被填满。

Here follows the alternative solution I tested on Chrome 49 and Firefox 45.
In the css stylesheet set the display property as 'none', like this:

下面是我在 Chrome 49 和 Firefox 45 上测试的替代解决方案
。 在 css 样式表中将 display 属性设置为“none”,如下所示:

#img_gif{
  display:'none';
}

Outside the '$(document).ready' statement insert:

在 '$(document).ready' 语句外插入:

$(window).load(function(){ $('#img_gif').show(); });

$(window).load(function(){ $('#img_gif').show(); });

Every time the user accesses the page, the animation will be started after the complete load of all the elements. This is the only way I found to sincronize gif and html5 animations.

每次用户访问页面时,动画都会在所有元素加载完成后开始。这是我发现对 gif 和 html5 动画进行 sincronize 的唯一方法。

Please note that:
The gif animation will not restart after refreshing the page (like pressing "F5").
The "$(document).ready" statement doesn't produce the same effect of "$(window).load".
The property "visibility" doesn't produce the same effect of "display".

请注意:
gif 动画不会在刷新页面后重新启动(如按“F5”)。
“$(document).ready”语句不会产生与“$(window).load”相同的效果。
属性“可见性”不会产生与“显示”相同的效果。

回答by Vincent Tang

Related answer, you can specify the number of playbacks on a gif. The below gif has 3 playbacks associated with it (10 second timer, 30 second playback total). After 30 seconds have passed since page load, it stops at "0:01".

相关答案,您可以指定 gif 的播放次数。下面的 gif 有 3 个与之相关的回放(10 秒计时器,总共 30 秒回放)。页面加载 30 秒后,它在“0:01”停止。

Refresh the page to restart all 3 playbacks

刷新页面以重新开始所有 3 次播放

You have to modify the gif itself. An easy tool is found here for modifying GIF playbacks https://ezgif.com/loop-count.

您必须修改 gif 本身。在这里可以找到一个简单的工具来修改 GIF 播放https://ezgif.com/loop-count

To see an example of a single-loop playback gif in action on a landing page, checkout this site using a single playback gif https://git-lfs.github.com/

要在登录页面上查看单循环播放 gif 的示例,请使用单个播放 gif 查看此站点https://git-lfs.github.com/

enter image description here

在此处输入图片说明

回答by Sourabh

found a working solution here: https://codepen.io/hoanghals/pen/dZrWLZ

在这里找到了一个有效的解决方案:https: //codepen.io/hoanghals/pen/dZrWLZ

JS here:

JS在这里:

var gifElements = document.querySelectorAll('img.gif');

for(var e in gifElements) {

var element = gifElements[e];

if(element.nodeName == 'IMG') {

    var supergif = new SuperGif({
        gif: element,
        progressbar_height: 0,
        auto_play: false,
    });

    var controlElement = document.createElement("div");
    controlElement.className = "gifcontrol loading g"+e;

    supergif.load((function(controlElement) {
        controlElement.className = "gifcontrol paused";
        var playing = false;
        controlElement.addEventListener("click", function(){
            if(playing) {
                this.pause();
                playing = false;
                controlElement.className = "gifcontrol paused";
            } else {
                this.play();
                playing = true;
                controlElement.className = "gifcontrol playing";
            }
        }.bind(this, controlElement));

    }.bind(supergif))(controlElement));

    var canvas = supergif.get_canvas();     
    controlElement.style.width = canvas.width+"px";
    controlElement.style.height = canvas.height+"px";
controlElement.style.left = canvas.offsetLeft+"px";
    var containerElement = canvas.parentNode;
    containerElement.appendChild(controlElement);

 }
}