我如何隐藏破碎的图像图标? 例子:

我有一个图像与错误src:

<img src="Error.src"/>

该解决方案必须适用于所有浏览器。


当前回答

可以使用before和after作为样式,以防止图像损坏。

<img src="Error.src">

img:before {
  content: url("image.jpg");
}

img:after {
  content: "(url: " attr(src) ")";
}

在这种情况下,如果src中的图像被破坏了,它将使用之前的内容,如果没有错误,它将使用src。

其他回答

使用img::after的技巧是一个好东西,但至少有两个缺点:

并非所有浏览器都支持(例如在Edge https://codepen.io/dsheiko/pen/VgYErm上不支持) 你不能简单地隐藏图像,你要覆盖它-所以当你在这种情况下显示默认图像时没有什么帮助

我不知道没有JavaScript的通用解决方案,但只有Firefox有一个不错的:

img:-moz-broken{
  opacity: 0;
}

缺失的图像要么什么都不显示,要么显示一个[?]样式框,当无法找到它们的源时。相反,你可能想用一个你确定存在的“缺失的图像”图形来替换它,这样就有更好的视觉反馈,表明有问题。或者,你可能想把它完全隐藏起来。这是可能的,因为浏览器无法找到的图像会触发我们可以观察的“错误”JavaScript事件。

    //Replace source
    $('img').error(function(){
            $(this).attr('src', 'missing.png');
    });

   //Or, hide them
   $("img").error(function(){
           $(this).hide();
   });

此外,当发生这种情况时,您可能希望触发某种Ajax操作,向站点管理员发送电子邮件。

一种不需要任何代码的基本且非常简单的方法是只提供一个空的alt语句。然后浏览器将返回空白图像。它看起来就像没有图像一样。

例子:

<img class="img_gal" alt="" src="awesome.jpg">

试试看吧!;)

在https://bitsofco.de/styling-broken-images/找到了一个很好的解决方案

img { position: relative; } /* style this to fit your needs */ /* and remove [alt] to apply to all images*/ img[alt]:after { display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #fff; font-family: 'Helvetica'; font-weight: 300; line-height: 2; text-align: center; content: attr(alt); } <img src="error"> <br> <img src="broken" alt="A broken image"> <br> <img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png" alt="A bird" style="width: 120px">

我认为最简单的方法是通过text-indent属性隐藏损坏的图像图标。

img {
    text-indent: -10000px
}

显然,如果你想看到“alt”属性,它就不起作用了。