这对我来说似乎是个坏主意。此功能的目的是什么?听起来你想要与此等效的东西:
<img src="/images/file1.jpg" src2="/images/file2.jpg" src3="/images/file3.jpg">
浏览器将连续尝试每个文件。这种方法的问题在于它显着增加了所需的 http 流量和延迟。最好的方法是提前使用正确的图像标签动态构建页面。使用服务器端方法,您可以尝试从磁盘(或数据库或图像所在的任何位置)加载图像,并在页面的图像标记中动态包含最佳 URL。
如果您坚持在客户端执行此操作,可以尝试加载多个图像标签:
<img src="file1.jpg" alt="" onerror="this.style.display='none'">
<img src="file2.jpg" alt="" onerror="this.style.display='none'">
<img src="file3.jpg" alt="" onerror="this.style.display='none'">
<img src="file4.jpg" alt="" onerror="this.style.display='none'">
<img src="file5.jpg" alt="" onerror="this.style.display='none'">
<img src="file6.jpg" alt="" onerror="this.style.display='none'">
这将导致页面看起来有很多图像,但它们会随着页面加载而消失。这alt=""
需要让 Opera 不显示损坏的图像占位符;这onerror
Chrome 和 IE 需要。
如果这还不够漂亮,并且所有图像的尺寸相同,并且该尺寸已知,则可以将一堆图像一个一个地堆叠在另一个之上,以便加载的第一个图像隐藏所有其他图像。这对我在 Opera、FF 和 IE8 中都有效。它加载存在的列表中的最后一个图像。请注意,这会浪费带宽和内存,因为每个图像都会被加载。
<div style="width: 50px; height:38px; background-image: url(file1.jpg);">
<div style="width: 50px; height:38px; background-image: url(file2.jpg);">
<div style="width: 50px; height:38px; background-image: url(file3.jpg);">
<div style="width: 50px; height:38px; background-image: url(file4.jpg);">
<div style="width: 50px; height:38px; background-image: url(file5.jpg);">
<div style="width: 50px; height:38px; background-image: url(file6.jpg);">
<div style="width: 50px; height:38px; background-image: url(file7.jpg);">
</div></div></div></div></div></div>
最后,还有 JavaScript 方法:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
var image_array = ['file1.jpg', 'file2.jpg', 'file3.jpg', 'file4.jpg', 'file5.jpg','file6.jpg' ];
function load_img(imgId, image, images, index) {
image.onerror = function() {
load_img(imgId, this, images, index+1);
};
image.onload = function() {
var element = document.getElementById(imgId);
if (element) {
element.src = this.src;
element.style.display = 'block';
}
};
image.src = images[index];
}
</script>
</head>
<body>
<img id="id_1" alt="" style="display: none;">
</body>
<script>
load_img('id_1', new Image(), image_array, 0);
</script>
</html>