如何仅使用 CSS/HTML 隐藏图像损坏的图标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22051573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:03:53  来源:igfitidea点击:

How to hide image broken Icon using only CSS/HTML?

htmlcssimage

提问by Geray Suinov

How can I hide the broken image icon? Example: Example

如何隐藏损坏的图像图标? 示例例子

I have an image with error src:

我有一个带有错误 src 的图像:

<img src="Error.src"/>

The solution must work in all browsers.

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

回答by Kevin Jantzer

There is no way for CSS/HTML to know if the image is broken link, so you are going to have to use JavaScript no matter what

CSS/HTML 无法知道图像是否已断开链接,因此无论如何您都必须使用 JavaScript

But here is a minimal method for either hiding the image, or replacing the source with a backup.

但这是隐藏图像或用备份替换源的最小方法。

<img src="Error.src" onerror="this.style.display='none'"/>

or

或者

<img src="Error.src" onerror="this.src='fallback-img.jpg'"/>

Update

更新

You can apply this logic to multiple images at once by doing something like this:

您可以通过执行以下操作同时将此逻辑应用于多个图像:

document.addEventListener("DOMContentLoaded", function(event) {
   document.querySelectorAll('img').forEach(function(img){
   img.onerror = function(){this.style.display='none';};
   })
});
<img src="error.src">
<img src="error.src">
<img src="error.src">
<img src="error.src">

Update 2

更新 2

For a CSS optionsee michalzuber's answerbelow. You can't hide the entire image, but you change how the broken icon looks.

对于CSS 选项,请参阅下面michalzuber 的回答。您无法隐藏整个图像,但可以更改损坏图标的外观。

回答by Nick Steele

Despite what people are saying here, you don't need JavaScript at all, you don't even need CSS!!

不管人们在这里说什么,你根本不需要 JavaScript,你甚至不需要 CSS!

It's actually very doable and simple with HTML only. You can even show a default image if an image doesn't load. Here's how...

实际上,仅使用 HTML 就非常可行且简单。 如果图像未加载,您甚至可以显示默认图像。就是这样...

This also works on all browsers, even as far back as IE8 (out of 250,000+ visitors to sites I hosted in September 2015, ZEROpeople used something worse than IE8, meaning this solution works for literally everything).

这也适用于所有浏览器,甚至可以追溯到 IE8(在我 2015 年 9 月托管的网站的 250,000 多名访问者中,人使用了比 IE8 更糟糕的东西,这意味着该解决方案几乎适用于所有浏览器)。

Step 1: Reference the image as an objectinstead of an img. When objects fail they don't show broken icons; they just do nothing. Starting with IE8, you can use Object and Img tags interchangeably. You can resize and do all the glorious stuff you can with regular images too. Don't be afraid of the object tag; it's just a tag, nothing big and bulky gets loaded and it doesn't slow down anything. You'll just be using the img tag by another name. A speed test shows they are used identically.

步骤 1:将图像引用为对象而不是img。当对象失败时,它们不会显示损坏的图标;他们什么都不做。从 IE8 开始,您可以交替使用 Object 和 Img 标签。您也可以使用常规图像调整大小并执行所有出色的操作。不要害怕对象标签;它只是一个标签,不会加载任何大而笨重的东西,也不会减慢任何速度。您将只是使用另一个名称的 img 标签。速度测试表明它们的使用方式相同。

Step 2: (Optional, but awesome)Stick a default image inside that object. If the image you want actually loads in the object, the default image won't show. So for example you could show a list of user avatars, and if someone doesn't have an image on the server yet, it could show the placeholder image... no javascript or CSS required at all, but you get the features of what takes most people JavaScript.

第 2 步:(可选,但很棒)在该对象内粘贴默认图像。如果您想要的图像实际加载到对象中,则不会显示默认图像。例如,您可以显示用户头像列表,如果有人在服务器上还没有图像,它可以显示占位符图像...根本不需要 javascript 或 CSS,但您可以获得什么的功能需要大多数人使用 JavaScript。

Here is the code...

这是代码...

<object data="avatar.jpg" type="image/jpg">
    <img src="default.jpg" />
</object>

... Yes, it's that simple.

……是的,就是这么简单。

If you want to implement default images with CSS, you can make it even simpler in your HTML like this...

如果你想用 CSS 实现默认图像,你可以像这样在你的 HTML 中让它更简单......

<object class="avatar" data="user21.jpg" type="image/jpg"></object>

...and just add the CSS from this answer -> https://stackoverflow.com/a/32928240/3196360

...然后从这个答案中添加 CSS -> https://stackoverflow.com/a/32928240/3196360

回答by michalzuber

Found a great solution at https://bitsofco.de/styling-broken-images/

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

回答by P Satish Patro

If you will add alt with text alt="abc"it will show the show corrupt thumbnail, and alt message abc

如果您添加带有文本alt="abc" 的 alt,它将显示显示损坏的缩略图,以及 alt 消息 abc

<img src="pic_trulli.jpg" alt="abc"/>

1st

第一

If you will not add alt it will show the show corrupt thumbnail

如果您不添加 alt,它将显示显示损坏的缩略图

<img src="pic_trulli.jpg"/>

2nd

第二

If you want to hide the broken one just add alt=""it will not show corrupt thumbnail and any alt message(without using js)

如果您想隐藏损坏的,只需添加alt=""它不会显示损坏的缩略图和任何 alt 消息(不使用 js)

<img src="pic_trulli.jpg" alt=""/>

If you want to hide the broken one just add alt="" & onerror="this.style.display='none'"it will not show corrupt thumbnail and any alt message(with js)

如果您想隐藏损坏的,只需添加alt="" & onerror="this.style.display='none'"它不会显示损坏的缩略图和任何 alt 消息(使用 js)

<img src="pic_trulli.jpg" alt="abc" onerror="this.style.display='none'"/>

4th one is a little dangerous(not exactly) , if you want to add any image in onerror event, it will not display even if Image exist as style.display is like adding. So, use it when you don't require any alternative image to display.

第四个有点危险(不完全是),如果你想在 onerror 事件中添加任何图像,即使图像存在,它也不会显示,因为 style.display 就像添加一样。因此,当您不需要显示任何替代图像时,请使用它。

display: 'none'; // in css

If we give it in CSS, then the item will not display(like image, iframe, div like that).

如果我们在 CSS 中提供它,那么该项目将不会显示(如图像、iframe、div 之类)。

If you want to display image & you want to display totally blank space if error, then you can use, but also be careful this will not take any space. So, you need to keep it in a div may be

如果你想显示图像&如果错误你想显示完全空白,那么你可以使用,但也要注意这不会占用任何空间。所以,你需要把它保存在一个 div 中可能是

Link https://jsfiddle.net/02d9yshw/

链接https://jsfiddle.net/02d9yshw/

回答by Burnee

I think the easiest way is to hide the broken image icon by the text-indent property.

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

img {
    text-indent: -10000px
}

Obviously it doesn't work if you want to see the "alt" attribute.

显然,如果您想查看“alt”属性,它是行不通的。

回答by Bartezz

I liked the answerby Nickand was playing around with this solution. Found a cleaner method. Since ::before/::after pseudos don't work on replaced elements like img and object they will only work if the object data (src) is not loaded. It keeps the HTML more clean and will only add the pseudo if the object fails to load.

我喜欢Nick回答,并且正在尝试这个解决方案。找到了一个更干净的方法。由于 ::before/::after 伪指令不适用于 img 和 object 等替换元素,因此它们仅在未加载对象数据 (src) 时才有效。它使 HTML 更干净,并且只会在对象加载失败时添加伪代码。

object {
  position: relative;
  float: left;
  display: block;
  width: 200px;
  height: 200px;
  margin-right: 20px;
  border: 1px solid black;
}
object::after {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: 100%;
  content: '';
  background: red url("http://placehold.it/200x200");
}
<object data="http://lorempixel.com/200/200/people/1" type="image/png"></object>

<object data="http://broken.img/url" type="image/png"></object>

回答by Ewald Bos

in the case you like to keep/need the image as a placeholder, you could change the opacity to 0 with an onerror and some css to set the image size. This way you will not see the broken link, but the page loads as normal.

如果您想保留/需要图像作为占位符,您可以使用 onerror 和一些 css 将不透明度更改为 0 来设置图像大小。这样您就不会看到断开的链接,但页面会正常加载。

<img src="<your-image-link->" onerror="this.style.opacity='0'" />

.img {
    width: 75px;
    height: 100px;
}

回答by user2596313

If you need to still have the image container visible due to it being filled in later on and don't want to bother with showing and hiding it you can stick a 1x1 transparent image inside of the src:

如果您仍然需要让图像容器可见,因为它稍后会被填充并且不想打扰显示和隐藏它,您可以在 src 内粘贴一个 1x1 透明图像:

<img id="active-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"/>

<img id="active-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"/>

I used this for this exact purpose. I had an image container that was going to have an image loaded into it via Ajax. Because the image was large and took a bit to load, it required setting a background-image in CSS of a Gif loading bar.

我将其用于此确切目的。我有一个图像容器,它将通过 Ajax 将图像加载到其中。由于图片较大,加载时间较长,因此需要在 Gif 加载栏的 CSS 中设置背景图片。

However, because the src of the was empty, the broken image icon still appeared in browsers that use it.

但是,由于 src 为空,损坏的图像图标仍然出现在使用它的浏览器中。

Setting the transparent 1x1 Gif fixes this problem simply and effectively with no code additions through CSS or JavaScript.

设置透明的 1x1 Gif 可以简单有效地解决这个问题,无需通过 CSS 或 JavaScript 添加代码。

回答by Dryden Long

Using CSS only is tough, but you could use CSS's background-imageinstead of <img>tags...

仅使用 CSS 很难,但您可以使用 CSSbackground-image代替<img>标签……

Something like this:

像这样的东西:

HTML

HTML

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

CSS

CSS

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

}

Here is a working fiddle.

这是一个工作小提琴

Note: I added the border in the CSS on the fiddle just to demonstrate where the image would be.

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

回答by ThomasAFink

Use the object tag. Add alternative text between the tags like this:

使用对象标签。在标签之间添加替代文本,如下所示:

<object data="img/failedToLoad.png" type="image/png">Alternative Text</object>

http://www.w3schools.com/tags/tag_object.asp

http://www.w3schools.com/tags/tag_object.asp