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

我有一个图像与错误src:

<img src="Error.src"/>

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


当前回答

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

例子:

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

试试看吧!;)

其他回答

只使用CSS是很困难的,但是你可以使用CSS的background-image而不是<img>标签…

就像这样:

HTML

<div id="image"></div>

CSS

#image {
    background-image: url(Error.src);
    width: //width of image;
    height: //height of image;

}

这是一把能用的小提琴。

注意:我在CSS中添加边界只是为了演示图像的位置。

在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">

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

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

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

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

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

img {
    text-indent: -10000px
}

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

其他人所描述的同样的想法在React中工作如下:

<img src='YOUR-URL' onError={(e) => e.target.style.display='none' }/>