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

发布于 2024-11-03 16:55:12 字数 462 浏览 8 评论 0原文

我有一个包含很多 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="" >

我要查找的内容

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

2 鼠标悬停 =>动画从该 gif 开始

3 鼠标移开 =>动画再次停止该 gif

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

I have a page with a lot of GIFs.

<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

2 On mouseover => Animations starts for that one gif

3 On mouseout => Animation stops again for that gif

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

谜兔 2024-11-10 16:55:12

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

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

示例:

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

更新:

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

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.

歌入人心 2024-11-10 16:55:12

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

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

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

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

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

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

id="imgAnimate"

这将在鼠标悬停时加载 gif,因此看起来您的图像开始移动。 (这比加载 gif 更好,因为从静态图像到 gif 的转换会断断续续,因为 gif 将从随机帧开始)

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

<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>

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

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)

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.

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

$(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.

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)

for more than one image just recreate the script create 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.

绿光 2024-11-10 16:55:12

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

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

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

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

老子叫无熙 2024-11-10 16:55:12

最好的选择可能是使用静态图像,当您想要停止它时可以用它替换 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");
    });

您可能想要有两个数组,其中包含可以分配给每个图像的静态和动画 gif 的路径。

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

    <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.

青春有你 2024-11-10 16:55:12

纯 JS 实现 https://jsfiddle.net/clayrabbit/k2ow48cy/
(基于 https://codepen.io/hoanghals/pen/dZrWLZ 的画布解决方案)

[].forEach.call(document.querySelectorAll('.myimg'), function(elem) {
    var img = new Image();
    img.onload = function(event) {
    elem.previousElementSibling.getContext('2d').drawImage(img, 0, 0);
    };
  img.src = elem.getAttribute('data-src');
  
    elem.onmouseover = function(event) {
        event.target.src = event.target.getAttribute('data-src');
    };
    elem.onmouseout = function(event) {
        event.target.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
    };
});
.mydiv{
  width: 320px;
  height: 240px;
  position: relative;
}
.mycanvas, .myimg {
  width: 100%;
  height: 100%;
  position: absolute;
}
<div class="mydiv">
<canvas class="mycanvas" width=320 height=240></canvas>
<img class="myimg" data-src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif">
</div>

Pure JS implementation https://jsfiddle.net/clayrabbit/k2ow48cy/
(based on canvas solution from https://codepen.io/hoanghals/pen/dZrWLZ)

[].forEach.call(document.querySelectorAll('.myimg'), function(elem) {
    var img = new Image();
    img.onload = function(event) {
    elem.previousElementSibling.getContext('2d').drawImage(img, 0, 0);
    };
  img.src = elem.getAttribute('data-src');
  
    elem.onmouseover = function(event) {
        event.target.src = event.target.getAttribute('data-src');
    };
    elem.onmouseout = function(event) {
        event.target.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
    };
});
.mydiv{
  width: 320px;
  height: 240px;
  position: relative;
}
.mycanvas, .myimg {
  width: 100%;
  height: 100%;
  position: absolute;
}
<div class="mydiv">
<canvas class="mycanvas" width=320 height=240></canvas>
<img class="myimg" data-src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif">
</div>

自由如风 2024-11-10 16:55:12

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

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

 }
}

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

JS here:

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

 }
}
倾城°AllureLove 2024-11-10 16:55:12

这个答案建立在 Sourabh 的基础上,他在 https://codepen 中指出了 HTML/CSS/JavaScript 组合.io/hoanghals/pen/dZrWLZ 完成了这项工作。我尝试了这个,并制作了一个完整的网页,包括 CSS 和 JavaScript,我在我的网站上尝试过。由于CodePens有消失的习惯,所以我决定在这里展示它。我还展示了一个简化的精简版本,以演示人们需要做的最低限度的事情。

我还必须注意一件事。上述链接中的代码(其 JavaScript Sourabh 复制)引用了 JavaScript 构造函数 SuperGif() 。我认为 Sourabh 没有解释过这一点,CodePen 也没有解释过。简单的搜索表明它是在buzzfeed /中定义的
libgif-js ,可以从 https://github.com/buzzfeed/libgif-js 下载#自述文件。找到下面红色箭头所指的控件,然后单击绿色的“代码”按钮。 (注意,您不会看到红色箭头:这是我向您展示的位置。)

buzzfeed/libgif-js 的 GitHub 页面的屏幕截图

将弹出一个菜单,提供各种选项,包括下载 zip 文件。下载它,并将其解压到您的 HTML 目录或其子目录中。

接下来,我将展示我制作的两个页面。第一个源自 CodePen。第二个内容被精简到最基本的内容,并显示了使用 SuperGif 所需的最低限度的内容。

这是第一页的完整 HTML、CSS 和 JavaScript。 HTML 的头部是 libgif.js 的链接,这是您需要从 zip 文件中获取的文件。然后,HTML 正文以一些有关猫图片的文本开始,后面是动画猫 GIF 的链接,网址为 https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif

然后继续一些 CSS。 CodePen 使用 SCSS,对于任何不知道的人来说,必须将其预处理为 CSS。我已经这样做了,所以下面的代码中的内容是真正的 CSS。

最后是 JavaScript。

<html>
<head>
<script src="libgif-js-master/libgif.js"></script> 
</head>

<body>

<div style="width: 600px; margin: auto; text-align: center; font-family: arial">
  <p>
And so, the unwritten law of the internet, that any 
experiment involving video/images must involve cats in 
one way or another, reared its head again. When would 
the internet's fascination with cats come to an end? 
Never. The answer is "Never".
</p> 
  <img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</div>

<style>
img.gif {
  visibility: hidden;
}

.jsgif {
  position: relative;
}

.gifcontrol {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  cursor: pointer;
  transition: background 0.25s ease-in-out;
  z-index: 100;
}
.gifcontrol:after {
  transition: background 0.25s ease-in-out;
  position: absolute;
  content: "";
  display: block;
  left: calc(50% - 25px);
  top: calc(50% - 25px);
}
.gifcontrol.loading {
  background: rgba(255, 255, 255, 0.75);
}
.gifcontrol.loading:after {
  background: #FF9900;
  width: 50px;
  height: 50px;
  border-radius: 50px;
}
.gifcontrol.playing {
  /* Only show the 'stop' button on hover */
}
.gifcontrol.playing:after {
  opacity: 0;
  transition: opacity 0.25s ease-in-out;
  border-left: 20px solid #FF9900;
  border-right: 20px solid #FF9900;
  width: 50px;
  height: 50px;
  box-sizing: border-box;
}
.gifcontrol.playing:hover:after {
  opacity: 1;
}
.gifcontrol.paused {
  background: rgba(255, 255, 255, 0.5);
}
.gifcontrol.paused:after {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 25px 0 25px 50px;
  border-color: transparent transparent transparent #ff9900;
}
</style>

<script>
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);
    
  }
}
</script>

</body>
</html>

当我将页面放在我的网站上并显示它时,顶部如下所示:

带有猫的暂停动画 GIF 的网页

当我按下粉红色按钮时,页面变成了这样,并且 GIF 开始动画。 (猫舔着从水龙头流下的水。)

带有猫的运行动画 GIF 的网页

最后,这是第二个简单的页面。与第一个不同,它没有一个可以改变形状的奇特的播放/暂停控件:它只有两个按钮。该代码所做的唯一不是必需的事情是禁用不相关的按钮,并在按钮之间插入一些空格。

<html>

<head>
<script src="libgif-js-master/libgif.js"></script>
</head>

<body>

<button type="button" onclick="play()"
        id="play_button"
        style="margin-right:9px;"
>
Play
</button>
      
<button type="button" onclick="pause()"
        id="pause_button"
>
Pause
</button>

<img src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif" 
     id="gif" 
/>

<script>
var gif_element = document.getElementById( "gif" );
    
var supergif = new SuperGif( {
             gif: gif_element,
                          progressbar_height: 0,
                          auto_play: false
               } );

supergif.load();

function play()
{
  var play_button = document.getElementById( "play_button" );
  play_button.disabled = true;

  var pause_button = document.getElementById( "pause_button" );
  pause_button.disabled = false;
 
  supergif.play();
}

function pause()
{
  var play_button = document.getElementById( "play_button" );
  play_button.disabled = false;

  var pause_button = document.getElementById( "pause_button" );
  pause_button.disabled = true;

  supergif.pause();
}

pause_button.disabled = true;
</script>

</body>
</html>

这加上 libgif-js 中的 example.html 文件应该足以让任何人开始。

This answer builds on that of Sourabh, who pointed out an HTML/CSS/JavaScript combo at https://codepen.io/hoanghals/pen/dZrWLZ that did the job. I tried this, and made a complete web page including the CSS and JavaScript, which I tried on my site. As CodePens have a habit of disappearing, I decided to show it here. I'm also showing a simplified stripped-to-essentials version, to demonstrate the minimum that one needs to do.

I must also note one thing. The code at the above link, whose JavaScript Sourabh copies, refers to a JavaScript constructor SuperGif() . I don't think Sourabh explained that, and neither does the CodePen. An easy search showed that it's defined in buzzfeed /
libgif-js , which can be downloaded from https://github.com/buzzfeed/libgif-js#readme . Look for the control that the red arrow below is pointing at, then click on the green "Code" button. (N.B. You won't see the red arrow: that's me showing you where to look.)

Screenshot of GitHub page for buzzfeed/libgif-js

A menu will pop up offering various options including to download a zip file. Download it, and extract it into your HTML directory or a subdirectory thereof.

Next, I'm going to show the two pages that I made. The first is derived from the CodePen. The second is stripped to its essentials, and shows the minimum you need in order to use SuperGif.

So here's the complete HTML, CSS, and JavaScript for the first page. In the head of the HTML is a link to libgif.js , which is the file you need from the zip file. Then, the body of the HTML starts with some text about cat pictures, and follows it with a link to an animated cat GIF at https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif .

It then continues with some CSS. The CodePen uses SCSS, which for anyone who doesn't know, has to be preprocessed into CSS. I've done that, so what's in the code below is genuine CSS.

Finally, there's the JavaScript.

<html>
<head>
<script src="libgif-js-master/libgif.js"></script> 
</head>

<body>

<div style="width: 600px; margin: auto; text-align: center; font-family: arial">
  <p>
And so, the unwritten law of the internet, that any 
experiment involving video/images must involve cats in 
one way or another, reared its head again. When would 
the internet's fascination with cats come to an end? 
Never. The answer is "Never".
</p> 
  <img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</div>

<style>
img.gif {
  visibility: hidden;
}

.jsgif {
  position: relative;
}

.gifcontrol {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  cursor: pointer;
  transition: background 0.25s ease-in-out;
  z-index: 100;
}
.gifcontrol:after {
  transition: background 0.25s ease-in-out;
  position: absolute;
  content: "";
  display: block;
  left: calc(50% - 25px);
  top: calc(50% - 25px);
}
.gifcontrol.loading {
  background: rgba(255, 255, 255, 0.75);
}
.gifcontrol.loading:after {
  background: #FF9900;
  width: 50px;
  height: 50px;
  border-radius: 50px;
}
.gifcontrol.playing {
  /* Only show the 'stop' button on hover */
}
.gifcontrol.playing:after {
  opacity: 0;
  transition: opacity 0.25s ease-in-out;
  border-left: 20px solid #FF9900;
  border-right: 20px solid #FF9900;
  width: 50px;
  height: 50px;
  box-sizing: border-box;
}
.gifcontrol.playing:hover:after {
  opacity: 1;
}
.gifcontrol.paused {
  background: rgba(255, 255, 255, 0.5);
}
.gifcontrol.paused:after {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 25px 0 25px 50px;
  border-color: transparent transparent transparent #ff9900;
}
</style>

<script>
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);
    
  }
}
</script>

</body>
</html>

When I put the page on my website and displayed it, the top looked like this:

Web page with paused animated GIF of cat

And when I pressed the pink button, the page changed to this, and the GIF started animating. (The cat laps water falling from a tap.)

Web page with running animated GIF of cat

To end, here's the second, simple, page. Unlike the first, this doesn't have a fancy Play/Pause control that changes shape: it just has two buttons. The only thing the code does that isn't essential is to disable whichever button is not relevant, and to insert some space between the buttons.

<html>

<head>
<script src="libgif-js-master/libgif.js"></script>
</head>

<body>

<button type="button" onclick="play()"
        id="play_button"
        style="margin-right:9px;"
>
Play
</button>
      
<button type="button" onclick="pause()"
        id="pause_button"
>
Pause
</button>

<img src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif" 
     id="gif" 
/>

<script>
var gif_element = document.getElementById( "gif" );
    
var supergif = new SuperGif( {
             gif: gif_element,
                          progressbar_height: 0,
                          auto_play: false
               } );

supergif.load();

function play()
{
  var play_button = document.getElementById( "play_button" );
  play_button.disabled = true;

  var pause_button = document.getElementById( "pause_button" );
  pause_button.disabled = false;
 
  supergif.play();
}

function pause()
{
  var play_button = document.getElementById( "play_button" );
  play_button.disabled = false;

  var pause_button = document.getElementById( "pause_button" );
  pause_button.disabled = true;

  supergif.pause();
}

pause_button.disabled = true;
</script>

</body>
</html>

This, plus the example.html file in libgif-js, should be enough to get anyone started.

依 靠 2024-11-10 16:55:12

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

标记:

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

css:

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

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

显然,这可以进一步优化,但为了便于阅读,我简化了这个示例

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/):

the markup:

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

the css:

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

the 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

祁梦 2024-11-10 16:55:12

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');
});

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

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

并且 img el 看起来像这样:

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

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

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

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 class="animated-img" src=".../img.jpg" data-gif-src=".../gif.gif" />

Note: This code is untested but should work fine.

撩发小公举 2024-11-10 16:55:12

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

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

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

$('#img_gif').attr('src','file.gif?' + Math.random());
暗喜 2024-11-10 16:55:12

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

刷新页面重新启动所有 3 次播放

您必须修改 gif 本身。这里有一个简单的工具,用于修改 GIF 播放 https://ezgif.com/loop-count

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

在此处输入图像描述

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".

Refresh the page to restart all 3 playbacks

You have to modify the gif itself. An easy tool is found here for modifying GIF playbacks 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/

enter image description here

绾颜 2024-11-10 16:55:12

据我所知,只有一种方法。

有 2 个图像,第一个是带有 gif 的第一帧(或任何你想要的)的 jpeg 和实际的 gif。

加载带有 jpeg 的页面,并在鼠标悬停时将 jpeg 替换为 gif。如果您愿意,您可以预加载 gif,或者如果它们尺寸较大,则可以在加载 gif 时显示加载,然后用它替换 jpeg。

如果你希望它是双线性的,就像鼠标悬停时播放 gif,鼠标移出时停止播放,然后从停止的帧继续播放,那么这不能通过 javascript+gif 组合来完成。

There is only one way from what I am aware.

Have 2 images, first a jpeg with first frame(or whatever you want) of the gif and the actual gif.

Load the page with the jpeg in place and on mouse over replace the jpeg with the gif. You can preload the gifs if you want or if they are of big size show a loading while the gif is loading and then replace the jpeg with it.

If you whant it to bi linear as in have the gif play on mouse over, stop it on mouse out and then resume play from the frame you stopped, then this cannot be done with javascript+gif combo.

白色秋天 2024-11-10 16:55:12

添加这样的后缀:

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

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

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

#img_gif{
  display:'none';
}

在“$(document).ready”语句之外插入:

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

每次用户访问页面时,动画都会在所有元素加载完成后启动。这是我发现的将 gif 和 html5 动画同步化的唯一方法。

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

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:

#img_gif{
  display:'none';
}

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

$(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.

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".

温柔嚣张 2024-11-10 16:55:12

css 过滤器可以阻止 gif 在 chrome 中播放,

只需添加

filter: blur(0.001px);

到您的 img 标签,然后 gif 冻结以通过 chrome 性能问题加载:)

css filter can stop gif from playing in chrome

just add

filter: blur(0.001px);

to your img tag then gif freezed to load via chrome performance concern :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文