如何让gif动画从头开始播放

发布于 2024-12-03 17:46:34 字数 164 浏览 0 评论 0原文

我在隐藏的 div 中有一个动画 gif 图像。恰好在 7 秒页面加载后,div 就会显示出来,因此图像也会显示出来。现在我的问题是,当页面第一次加载时,div 按其应有的方式显示,并且 gif 从头开始​​播放,但第二次开始就变得疯狂了。当 div 显示时,gif 图像会从动画中间的某个位置播放。有什么想法吗?

i've an animated gif image within a hidden div. Exactly after 7seconds page has loaded the div shows up and hence the image. Now my problem is that when the page is loaded for first time div shows up as it should and gif plays from the beginning but second time onwards it goes mad. When the div shows up gif image plays from somewhere in the middle of animation. any idea?

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

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

发布评论

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

评论(2

对岸观火 2024-12-10 17:46:34

Gif 会逐步加载,一旦有足够的数据来显示整个帧,就会开始播放。奇怪的是,它加载的秒数应该移到中间。

这可能是因为第二次 gif 被缓存并立即开始播放,而页面的其余部分需要一些时间才能加载。

你可以用 JavaScript 来解决这个问题。当您想要启动 gif 时,选择 img 元素并将其 src 属性更改为同一元素。这应该会触发重新加载,以便重新开始。由于它已被缓存,因此延迟应该最小。

Gifs load progressively and start playing as soon as there's enough data to show a whole frame. It's strange that the seconds time it load it should move to the middle.

It's likely because the second time the gif is cached and starts playing right away, and the rest of the page takes some time to load.

You could address this with javascript. At the time you want to start the gif, select the img element and change it's src attribute for the same one. That should trigger a reload so it will start over. And since it's cached, there should be minimal latency.

女中豪杰 2024-12-10 17:46:34

通常,您需要更新映像才能重新开始。但是,由于缓存的原因,您不能将其重新分配给同一个图像文件。例如,如果您有

<img id="timer" src="timer.gif">

并且使用 javascript 重新分配它:

document.querySelector("#timer").src = "timer.gif"

您的浏览器会说“哦,我以前看过该图像,我不需要重新加载它”,并且它不会工作。

但您可以通过添加唯一的查询字符串来欺骗它。该查询通常会被忽略,但会告诉浏览器这是新的东西,需要重新加载。所以尝试这样的事情:

document.querySelector("#timer").src = "timer.gif?" + Math.random();

Generally, you need to update the image to get it to start over. However, due to caching, you can't just reassign it to the same image file. For example, if you have

<img id="timer" src="timer.gif">

and you use javascript to reassign it:

document.querySelector("#timer").src = "timer.gif"

your browser will say "oh, I've seen that image before, I don't need to reload it" and it won't work.

But you can trick it by adding a unique query string. The query will generally be ignored, but will tell the browser it's something new that it needs to load fresh. So try something like this:

document.querySelector("#timer").src = "timer.gif?" + Math.random();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文