有没有办法在 HTML/JavaScript 中指定多个图像源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1630451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:08:12  来源:igfitidea点击:

Is there a way to designate multiple image sources in HTML/JavaScript?

htmlimage

提问by Imagist

Is there a way to tell the browser to look down a list of image URLs until it finds one that works? Pure HTML would be preferred, but I'm guessing JavaScript is probably necessary here (I'm already using JQuery, so it's not an issue).

有没有办法告诉浏览器查看图像 URL 列表,直到找到一个有效的?纯 HTML 将是首选,但我猜这里可能需要 JavaScript(我已经在使用 JQuery,所以这不是问题)。

EDIT: Thanks for your answers! I'll add a few clarifications:

编辑:感谢您的回答!我将添加一些说明:

  1. By "works" I mean the image can be displayed.
  2. I specifically want to do this on the client side.
  1. “作品”是指可以显示图像。
  2. 我特别想在客户端执行此操作。

采纳答案by u7867

This seems like a bad idea to me. What is the purpose of this feature? It sounds like you want something equivalent to this:

这对我来说似乎是个坏主意。此功能的目的是什么?听起来您想要与此等效的东西:

<img src="/images/file1.jpg" src2="/images/file2.jpg" src3="/images/file3.jpg">

Where the browser would try each file in succession. The problem with this approach is that it significantly increases the http traffic required and the latency. The best approach is to dynamically construct the page using the correct image tags ahead of time. Using a server-side approach you can try to load the image from the disk (or database or wherever the images are) and dynamically include the best url in the page's image tag.

浏览器将连续尝试每个文件的地方。这种方法的问题在于它显着增加了所需的 http 流量和延迟。最好的方法是提前使用正确的图像标签动态构建页面。使用服务器端方法,您可以尝试从磁盘(或数据库或图像所在的任何位置)加载图像,并在页面的图像标记中动态包含最佳 url。

If you insist on doing it client-side, you can try loading multiple image tags:

如果你坚持在客户端做,你可以尝试加载多个图像标签:

<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'">

This will result in a page that appears to have lots of images but they disappear as the page loads. The alt=""is required to make Opera not show the broken image placeholder; the onerroris required for Chrome and IE.

这将导致页面看起来有很多图像,但随着页面加载它们消失了。在alt=""需要使歌剧不显示破损图像占位符; 这onerror是 Chrome 和 IE 所必需的。

If that's not spiffy enough, and if all your images are the same size, and that size is known, you could stack a bunch of images one on top of the other, so that the first image that loads hides all the others. This worked for me in Opera, FF, and IE8. It loads the last image in the list that exists. Note that this wastes bandwidth and memory because every image is loaded.

如果这还不够漂亮,并且如果所有图像的大小都相同,并且该大小是已知的,那么您可以将一堆图像堆叠在一起,以便加载的第一个图像隐藏所有其他图像。这在 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>

Finally, there is the JavaScript approach:

最后,还有 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>

回答by Joey

If I am reading the specification correctly, you should be able to do this with the HTML objectelement. <object>tags can be nested and thereby provide a chain of resources that are tried each in turn to be rendered and upon failure the user agent continues with the next one.

如果我正确阅读了规范,您应该可以使用HTML objectelement做到这一点。<object>标签可以嵌套,从而提供一系列资源,这些资源依次尝试渲染,失败时用户代理继续下一个。

Note, though, that this behaviour is/was buggy for several browsers and versions.

但是请注意,对于多个浏览器和版本,此行为是/曾经是错误的。

回答by sekmo

If you're trying setting multiple sources to the image tag depending on the resolution, srcset is the paramenter you're looking for.

如果您尝试根据分辨率为图像标签设置多个源,则 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">

回答by StarScream

If by saying "works" you mean the image can be loaded, you can use the "load" function on an image( in your case a bunch of images) of jQuery and inside of it declare the functionality that will be fire once the loading of the an image is completed.

如果说“有效”是指可以加载图像,则可以在 jQuery 的图像(在您的情况下是一堆图像)上使用“加载”函数,并在其中声明加载后将触发的功能一张图片就完成了。

If by saying "works" you mean that the HTTP status code is ok then use an ajax call using jquery.

如果说“有效”是指 HTTP 状态代码正常,则使用 jquery 进行 ajax 调用。

function getUrlStatus(url) {
     $.ajax({
         url: url,
         complete: function(xhr) {
             return xhr.status;
         }
     });
 }

回答by jldupont

Assuming you mean the browser being able to retrieve some content with an HTTP response code 200 for a specific URL, then the answer is : NO from the client side using only HTML.

假设您的意思是浏览器能够使用特定 URL 的 HTTP 响应代码 200 检索某些内容,那么答案是:仅使用 HTML 的客户端不可以。

In other words, you can't have an element (e.g. img) and specify multiple URLs to "try".

换句话说,您不能拥有一个元素(例如 img)并指定多个 URL 来“尝试”。

Of course you can craft something on the server side: a request comes in for resource X and the server has a list of URLs that "work".

当然,您可以在服务器端制作一些东西:请求资源 X 并且服务器有一个“有效”的 URL 列表。

回答by Alex Mcp

INAJNBAM (I'm not a Javascript Ninja by any means), but in pseudo code, maybe try something like this after the page has loaded: (OR, now that I think about it, this would work well with PHP too)

INAJNBAM(无论如何我都不是 Javascript Ninja),但是在伪代码中,也许可以在页面加载后尝试这样的操作:(或者,现在我考虑了一下,这也适用于 PHP)

$images = array('img1.jpg', 'img2.jpg', 'img3.png'....)
    foreach $images as $img
        {if $img.height > 0px
            {print "<img src="$img" />"
            end}
        };;;;

In fact PHP would be even better because I presume in JS this would result in images flashing up on the screen at the end of the pageload. Try it out in PHP and see if something like this fits your bill.

事实上,PHP 会更好,因为我认为在 JS 中这会导致页面加载结束时图像在屏幕上闪烁。在 PHP 中尝试一下,看看这样的东西是否符合您的要求。

NOTE: I added 4 semi colons at the end. I know Javascript always wants 'em, I just didn't know where to stick them.

注意:我在最后添加了 4 个分号。我知道 Javascript 总是想要它们,我只是不知道把它们贴在哪里。

回答by rohancragg

You could enter the URL of some server-side application/script that serves up the image from whatever image source it can find.

您可以输入一些服务器端应用程序/脚本的 URL,该应用程序/脚本可以从它可以找到的任何图像源提供图像。

You could do this in ASP.Net with an HTTPHandler that sends a response of content-type=image/jpg.

您可以在 ASP.Net 中使用发送 content-type=image/jpg 响应的 HTTPHandler 执行此操作。

Other than ASP.Net there are amny other server-side options such as Perl, PHP...

除了 ASP.Net 之外,还有许多其他服务器端选项,例如 Perl、PHP...