Html 显示替代图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10772346/
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 00:40:30  来源:igfitidea点击:

Display alternate image

htmlcss

提问by rodedo

Is it possible to show an alternate image if the original source file is not found? I would like to achieve this only with css and html, no javascript (or jQuery and alike). The idea is to still show an image instead of the "alt" test or default (ugly) cross of IE. If not possible without javascript I will then rather check the img src with php with a basic if-then-else.

如果找不到原始源文件,是否可以显示替代图像?我只想用 css 和 html 来实现这一点,没有 javascript(或 jQuery 等)。这个想法是仍然显示图像而不是“alt”测试或IE的默认(丑陋)十字架。如果没有 javascript 不可能,那么我宁愿用 php 和基本的 if-then-else 检查 img src。

采纳答案by emrea

You can do this using the CSS background-image property of the img element, i.e.

你可以使用 img 元素的 CSS background-image 属性来做到这一点,即

img
{
background-image:url('default.png');
}

However, you have to give a width or height for this to work (when the img-src is not found):

但是,您必须为此提供宽度或高度(当找不到 img-src 时):

img
{
background-image:url('default.png');
width:400px;
}

回答by Magige Daniel

Very simple and best way to achieve this with little code

用很少的代码实现这一目标的非常简单和最好的方法

<img class="avatar" src="img/one.jpg" alt="Not Found" onerror=this.src="img/undefined.jpg">

To me the above works perfect!

对我来说,上述工作完美!

回答by Jukka K. Korpela

<object data="foobar.png" width=200 height=200>
  <img src="test.png" alt="Just testing.">
</object>

Here foobar.pngis the primary image, test.pngis the fallback image. By the semantics of the objectelement, the content of the element (here the imgelement) should be rendered if and only if the primary data (specified by the dataattribute) cannot be used.

foobar.png是主图像,test.png是后备图像。根据object元素的语义,img当且仅当data无法使用主要数据(由属性指定)时,才应呈现元素的内容(此处为元素)。

Though browsers have had awful bugs in implementations of objectin the past year, this simple technique seems to work on modern versions of IE, Firefox, Chrome.

尽管浏览器object在过去一年的实现中出现了可怕的错误,但这种简单的技术似乎适用于现代版本的 IE、Firefox、Chrome。

回答by Kalpesh Dabhi

yes, you can do it by using only html, when img src not found then it will throw error so here we can handle it. One more point is set this.onerror = null for recursive calling (default image not found)

是的,您可以仅使用 html 来完成,当找不到 img src 时,它会抛出错误,因此我们可以在这里处理它。还有一点是设置 this.onerror = null 用于递归调用(默认图片未找到)

<img alt="User Image" class="user-image" src="/Resources/images/user-icon.png" onerror="this.onerror=null; this.src='/Resources/images/user-icon.png'">