有没有一种方法可以告诉浏览器查看图像URL列表,直到找到可用的图像URL?纯HTML将是首选,但是我猜想JavaScript在这里可能是必要的(我已经在使用JQuery,所以这不是问题)。
编辑:感谢您的回答!我将添加一些说明:
这对我来说似乎是个坏主意。此功能的目的是什么?听起来您想要与此等效的东西:
<img src="/images/file1.jpg" src2="/images/file2.jpg" src3="/images/file3.jpg">
Run Code Online (Sandbox Code Playgroud)
浏览器将连续尝试每个文件的地方。这种方法的问题在于它显着增加了所需的 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'">
Run Code Online (Sandbox Code Playgroud)
这将导致页面看起来有很多图像,但随着页面加载它们消失了。在alt=""
需要使歌剧不显示破损图像占位符; 这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>
Run Code Online (Sandbox Code Playgroud)
最后,还有 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>
Run Code Online (Sandbox Code Playgroud)
如果您尝试根据分辨率为图像标签设置多个源,则 srcset 就是您要查找的参数。
<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 1x, images/space-needle-2x.jpg 2x,
images/space-needle-hd.jpg 3x">
Run Code Online (Sandbox Code Playgroud)