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


当前回答

我认为仅仅使用HTML是不可能的。然而,使用javascript,这应该是可行的。基本上我们循环每个图像,测试它是否完整,如果它的naturalWidth为零,那么这意味着它没有找到。代码如下:

fixBrokenImages = function( url ){
    var img = document.getElementsByTagName('img');
    var i=0, l=img.length;
    for(;i<l;i++){
        var t = img[i];
        if(t.naturalWidth === 0){
            //this image is broken
            t.src = url;
        }
    }
}

像这样使用它:

 window.onload = function() {
    fixBrokenImages('example.com/image.png');
 }

在Chrome和Firefox中测试

其他回答

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

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

你要求只有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文本。

使用Jquery,你可以这样做:

$(document).ready(function() {
    if ($("img").attr("src") != null)
    {
       if ($("img").attr("src").toString() == "")
       {
            $("img").attr("src", "images/default.jpg");
       }
    }
    else
    {
        $("img").attr("src", "images/default.jpg");
    }
});

angular2:

<img src="{{foo.url}}" onerror="this.src='path/to/altimg.png'">

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

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

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