嗯,我认为事情可能会更简单,如果你只使用img
标签,但如果你想使用背景图像,那么我只能想出一个解决办法。
诀窍是创建一个新的图像(使用the Javascript image object),并确保它已加载,但不显示此图像。一旦图像加载并在缓存中,该图像将在您的图库中作为背景图像提供。
因此,您所要做的就是确保在加载相应的图像后,您只能更改图像的背景图像LI
。您最初可以加载所有LI
s的默认“加载”图像。
所以,你的代码将是这样的:
HTML(该style
用于加载图像的定义可能是你外部样式表):
<ul>
<li id="pic1" style="background-image:url('images/loading.gif')"></li>
<li id="pic2" style="background-image:url('images/loading.gif')"></li>
<li id="pic3" style="background-image:url('images/loading.gif')"></li>
...
</ul>
你的jQuery/JavaScript的:
var img = new Array();
// The following would be in some sort of loop or array iterator:
var num = [NUMBER] // You'd use this number to keep track of multiple images.
// You could also do this by using $("ul>li").each() and using the index #
img[num] = new Image();
// Specify the source for the image
var imgSource = "http://yourimage.com/example.jpg";
// only append the corresponding LI after the image is loaded
img[num].onload = function() {
$("#pic" + num).attr("style", "background-image:url('" + imgSource + "')");
};
img[num].src = imgSource;
你将不得不为每个LI
有适当的CSS/ID等,你将不得不适应上述循环或功能你用来展示你的画廊。
Here's a jsFiddle example。 (为了测试的目的,这是一个很大的图像,所以需要一段时间才能加载)。
你有没有想过使用sprite ?,所以你只需要将1个图像加载到DOM中,然后每个图像被切片,就会使生活变得更简单,只需加载css表单onload事件为sprite图像,然后只需显示所有元素的加载器,直到加载CSS表单。 – RobertPitt 2010-08-16 10:39:03
不可能,图像来自DB – 2010-08-16 11:54:40