在新图片完全加载完成之前添加旋转器

9

这个脚本的作用是在点击时将image.jpg更改为newimage.gif,反之亦然。
现在我想在newimage.gif加载时添加一个旋转图标。
类似于9gag.com/gif上的那种。

有人可以帮我吗?

这是代码: html

<img src="/image.jpg" id="pic" onclick="change()"/>
<a id="first" href="/newimage.gif" style="display:none;"></a>
<a id="second" href="/image.jpg" style="display:none;"></a>

javascript

function change(){
var imag = document.getElementById('pic').src;
var img = imag.slice(-3);
var img1 = document.getElementById('second').href;
var imag2 = document.getElementById('first').href;

if(img == 'gif') {
document.getElementById('pic').src=imag2;
//    here the newimage.gif changes to image.jpg 
} else {
//    here the image.jpg changes to newimage.gif
//    i think here should be the code that will display a spinner while the image.gif loads completely
document.getElementById('pic').src=img1;
}
}
4个回答

23

最简单的方法可能是将图片的CSS background-image 属性设置为一个加载旋转器图形。

HTML:

<img src="path/to/real/image.jpg" class="loading">

CSS:

img.loading {
    background: transparent url(path/to/loading.gif) no-repeat scroll center center;
}

一旦实际图像被下载,它会覆盖“加载”动画GIF背景图像。

如果您有使用渐进式显示保存的GIF或JPG文件,则需要重新保存这些图像而不使用该选项,以便在完整的图像下载之前,实际图像是不可见的,同时允许您的旋转器图形显示出来。


我想要一个东西,在image.jpg被点击并且函数“change”开始后,检查image.gif何时完全加载。 - Marian07
嗯,你可以将“pic”图像的src切换为不可见的GIF或PNG,然后将CSS和类应用于IMG标记。然后立即将src设置为新图像。 - Greg Burghardt
我正在使用这个脚本在一个页面上,其中有许多gif图像。如果我想要预加载所有图像,我会使用<img id="first" href="/newimage.gif" style="display:none;"/>而不是<a id="first" href="/newimage.gif" style="display:none;"></a>。 - Marian07

0

你看过这个网站提供的可配置旋转器吗?它不需要额外的图形,可以附加到任何dom元素上。启动/停止旋转器只需要调用2个js函数。

该代码采用MIT许可证,最小化的js独立文件大小为9kb,提供了用作jQuery插件的粘合代码,并为那些“蒸汽朋克”浏览器提供了VML回退。

我与代码或作者没有任何关联。


0

0

我找到了一种方法,唯一的问题是在image.gif加载完成后,旋转器仍然出现。

if(img == 'gif') {
document.getElementById('pic').src=imag2;
//    here the newimage.gif changes back to image.jpg 
document.getElementById("spinner").style.display = "none";    
} else {
document.getElementById('pic').src=img1;

var image = new Image();
image.src = document.getElementById('second').href;

var x = image.complete;
if(x) {
document.getElementById("spinner").style.display = "none"; 
} else {
document.getElementById("spinner").style.display = "block";
}
}
}

这是我使用脚本的地方 http://www.2lol.ro/load/poze_haioase_miscatoare/20?ref=stk


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接