这对我来说似乎是个坏主意。此功能的目的是什么?听起来您想要与此等效的东西:
<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 不显示损坏的图像占位符;对于 Chrome 和 IE,onerror 是必需的。
如果这还不够漂亮,并且如果您的所有图像尺寸相同,并且该尺寸已知,您可以将一堆图像一个一个叠放在另一个之上,这样加载的第一个图像就会隐藏所有其他图像.这在 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>