重新启动动画GIF作为背景图像 [英] Restart animated GIF as background-image
问题描述
是否可以重新启动用作 background-image
的动画GIF?
Is it possible to restart an animated GIF used as background-image
?
/ p>
Consider this HTML:
<div id="face">
<div id="eyes"></eyes>
</div>
而且这种风格:
#eyes.blink {
background-image:url('blink.gif');
}
我想要 blink.gif
到 #eyes
,而不只是第一次添加 blink
I would like the blink.gif
animation to play every time I add the class blink
to #eyes
, not just the first time.
我预计这将工作:
function startBlink() {
$('#eyes').addClass('blink');
}
function stopBlink() {
$('#eyes').removeClass('blink');
}
问题是Firefox和WebKit浏览器都没有播放背景图片GIF动画再次播放一次。
The problem is that both Firefox and WebKit browser do not play a background-image GIF animation again once it has played once. Adding/removing the class blink only works the first time.
推荐答案
您可以通过重新加载动画gif进行重放。这不是理想的带宽,特别是如果你的图像是大的,但它会强制重新启动动画。
You can get the animated gif to replay by reloading it. This isn't ideal for bandwidth, especially if your image is large, but it will force a restart of the animation.
在我的例子中,我添加和删除它 onclick
of < div id =animated>
:
In my example I'm adding and removing it onclick
of <div id="animated">
:
$('#animated').click(function() {
/* Reference to the clicked element and toggle the .go class */
var $div = $(this);
$div.toggleClass('go');
/* Start the animated gif */
if ($div.hasClass('go')) {
/* Create an <img> element and give it the animated gif as a src. To
force a reload we add a date parameter to the URL */
var img = document.createElement('img');
img.src = "http://yoursite.com/animated.gif?p" + new Date().getTime();
/* Once the image has loaded, set it as the background-image */
$(img).load(function(){
$div.css({backgroundImage: "url("+img.src+")"});
});
/* Remove the background-image */
} else {
$div.css({backgroundImage: "none"});
}
})
Demo of it in action.
这篇关于重新启动动画GIF作为背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!