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


当前回答

这对我来说很有效。也许你想用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{…

其他回答

我认为仅仅使用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中测试

使用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");
    }
});

JQuery的可模块化版本,在文件末尾添加:

<script>
    $(function() {
        $('img[data-src-error]').error(function() {
            var o = $(this);
            var errorSrc = o.attr('data-src-error');

            if (o.attr('src') != errorSrc) {
                o.attr('src', errorSrc);
            }
        });
    });
</script>

在你的img标签上:

<img src="..." data-src-error="..." />

这对我来说很有效。也许你想用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{…

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