English 中文(简体)
显示替代图像
原标题:Display alternate image
  • 时间:2012-05-27 07:27:22
  •  标签:
  • html
  • css

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.

最佳回答

您可以使用 MIG 元素的背景图像属性, 即 :

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

然而,您必须给它一个宽度或高度才能工作( 当找不到 img- src) :

img
{
background-image:url( default.png );
width:400px;
}
问题回答

以小代码 实现此目标的简单和最佳方法

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

对我而言,以上是完美无缺的!

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

这里 foobar.png 是主图像, test.png 是后退图像。 根据 object 元素的语义,元素的内容(此处为 img 元素)只有在无法使用主数据(由 data 属性指定)时才应设定。

虽然在过去一年里浏览器在实施 ob object 时有可怕的错误,但这一简单技术似乎适用于现代版本的IE、Firefox、Chrome。

y, 您可以仅使用 html 来做到这一点, 当 img src 找不到 img src 时, 它会投出错误, 这样我们就可以在这里处理它 。 还有一个点是设置此. onerror = null 用于循环调用( 找不到默认图像) 。

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




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签