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


当前回答

上面的解决方案是不完整的,它错过了属性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';" />

其他回答

你要求只有HTML的解决方案…

<!DOCTYPE html PUBLIC "-//W3C//DTD html 4.01//EN" " http://www.w3.org/TR/html4/strict.dtd " > < html lang =“en”> <头> <标题>对象测试< /名称> <meta http-equiv=" content - type " content="text/html;charset = utf - 8”> > < /头 <身体> < p > <object data="https://stackoverflow.com/does-not-exist.png" type="image/png"> <img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45" alt="Stack Overflow徽标和图标等"> < /对象> < / p > < /身体> < / html >

由于第一个图像不存在,将显示回退(在这个网站上使用的精灵*)。如果你用的是不支持object的旧浏览器,它会忽略那个标签,使用img标签。查看caniuse网站了解兼容性。从IE6+开始的所有浏览器都广泛支持该元素。

*除非图片的URL改变了(再次),在这种情况下,你可能会看到alt文本。

反应

<img
  src="https://example.com/does_not_exist.png"
  onError={(e) => {
    e.currentTarget.src = "https://example.com/default.png"
  }}
/>

这对我来说很有效。也许你想用JQuery来挂钩事件。

 <img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';" alt="add alternative text here">

更新了jacquargs错误保护

更新:CSS唯一的解决方案 我最近看到Vitaly Friedman演示了一个我不知道的很棒的CSS解决方案。其思想是将内容属性应用于破碎的图像。通常:after或:before不应用于图像,但当它们被破坏时,它们就会被应用。

<img src="nothere.jpg" alt="add alternative text here">
<style>
img:before {
    content: ' ';
    display: block;
    position: absolute;
    height: 50px;
    width: 50px;
    background-image: url(ishere.jpg);
}
</style>

演示:https://jsfiddle.net/uz2gmh2k/2/

正如提琴所示,破碎的图像本身并没有被删除,但这可能会解决大多数情况下没有任何JS或CSS的问题。如果你需要在不同的位置应用不同的图像,只需用一个类进行区分:.my-special-case img:before{…

简单的img-element不是很灵活,所以我将它与picture-element结合在一起。这样就不需要CSS了。当发生错误时,所有srcset都被设置为回退版本。断开的链接图像不显示。它不会加载不需要的图像版本。图片元素支持响应式设计,并为浏览器不支持的类型提供多种回退。

<picture>
    <source id="s1" srcset="image1_not_supported_by_browser.webp" type="image/webp">
    <source id="s2" srcset="image2_broken_link.png" type="image/png">
    <img src="image3_fallback.jpg" alt="" onerror="this.onerror=null;document.getElementById('s1').srcset=document.getElementById('s2').srcset=this.src;">
</picture>

好了! ! 我发现这种方法很方便,检查图像的高度属性为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');
  }