是否有任何方法在HTML <img>标记中呈现默认图像,以防src属性无效(仅使用HTML)?如果不是,你会用什么轻量级的方式来解决这个问题?


当前回答

这是一个简单的Jquery,为我工作

        $(image).on('error', function(event) {
            imgage.attr('src', 'your_image.png');})

其他回答

在Spring in Action第三版中找到了这个解决方案。

<img src=“../资源/images/Image1.jpg”

更新: 这不是一个只有HTML的解决方案…Onerror是javascript

<style type="text/css">
img {
   background-image: url('/images/default.png')
}
</style>

请务必输入图像的尺寸,以及是否希望图像平铺。

谷歌抛出了这个页面的“图像回退html”关键字,但因为上面没有帮助我,我正在寻找一个“svg回退支持IE低于9”,我继续搜索,这是我发现的:

<img src="base-image.svg" alt="picture" />
<!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->

这可能离题了,但它解决了我自己的问题,也可能帮助到其他人。

上面的解决方案是不完整的,它错过了属性src。

这一点。src和this.attribute('src')是不一样的,第一个包含了对图像的完整引用,例如http://my.host/error.jpg,但属性只是保持原始值error.jpg

正确的解决方案

<img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />

好了! ! 我发现这种方法很方便,检查图像的高度属性为0,然后你可以用默认的图像覆盖src属性: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

 image.setAttribute('src','../icons/<some_image>.png');
  //check the height attribute.. if image is available then by default it will 
  //be 100 else 0
  if(image.height == 0){                                       
       image.setAttribute('src','../icons/default.png');
  }