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

我有一个图像与错误src:

<img src="Error.src"/>

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


当前回答

Angular隐藏破碎图像的方式。

Html文件内部

<img *ngIf="showImage" [src]="url" (error)="showImage = false">

内部Ts文件

public showImage = true;

其他回答

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

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

<img src="Error.src">

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

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

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

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

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

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

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

只使用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中添加边界只是为了演示图像的位置。

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

例子:

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

试试看吧!;)