如何仅使用CSS/HTML(不使用js)隐藏图像破损图标

时间:2022-11-25 16:51:40

How can I hide the broken image icon ? Example: 如何仅使用CSS/HTML(不使用js)隐藏图像破损图标

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

I have an image with error src:

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

<img src="Error.src"/>

The solution must work in all browsers.

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

Using only CSS or HTML, not JS.

只使用CSS或HTML,不使用JS。

13 个解决方案

#1


185  

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

For a CSS option see michalzuber's answer below. You can't hide the entire image, but you change how the broken icon looks.

有关CSS选项,请参阅下面的michalzuber的答案。你无法隐藏整个图像,但你可以改变坏掉的图标的样子。

#2


100  

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, ZERO people used something worse than IE8, meaning this solution works for literally everything).

这也适用于所有的浏览器,甚至可以追溯到IE8(在我2015年9月主持的网站的25万+访问者中,没有人使用比IE8更糟糕的东西,这意味着这个解决方案适用于所有东西)。

Step 1: Reference the image as an object instead 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开始,您可以交换地使用对象和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.

第二步:(可选,但很棒)在该对象中插入一个默认图像。如果要在对象中实际加载图像,则默认图像不会显示。例如,你可以显示一个用户头像列表,如果有人在服务器上还没有图片,它可以显示占位符图片……完全不需要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://*.com/a/32928240/3196360

…只需从这个答案中添加CSS—> https://*.com/a/32928240/3196360

#3


40  

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

#4


12  

I liked the answer by Nick and 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.

我很喜欢尼克的回答,并且在玩这个解决方案。发现了一个更清洁的方法。因为:before/::在pseudo之后不能处理替换的元素(如img和object),它们只在没有加载对象数据(src)时才能工作。它使HTML更简洁,并且只有在对象无法加载时才会添加pseudo。

http://codepen.io/anon/pen/xwqJKQ

http://codepen.io/anon/pen/xwqJKQ

<object data="http://lorempixel.com/200/200/people/1" type="image/png"></object>

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

object {
  position: relative;
  float: left;
  display: block;
  width: 200px;
  height: 200px;
  margin-right: 20px;
  border: 1px solid black;

  &::after {
    position: absolute;
    top: 0;
    left: 0;
    display: block;
    width: 100%;
    height: 100%;
    content: '';
    background: red url('http://placehold.it/200x200');
  }
}

#5


9  

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

我认为最简单的方法是将损坏的图像图标隐藏在文本缩进的属性中。

img {
    text-indent: -10000px
}

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

遗忘的是,如果你想看到alt属性,它就不能工作。

#6


8  

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

使用CSS非常困难,但是您可以使用CSS的背景图像而不是如何仅使用CSS/HTML(不使用js)隐藏图像破损图标标签…

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: http://jsfiddle.net/xbK6g/

这里有一个工作小提琴:http://jsfiddle.net/xbK6g/

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

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

#7


5  

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 = "动态图像" src = "数据:图像/ 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的src是空的,因此损坏的图像图标仍然出现在使用它的浏览器中。

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

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

#8


3  

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;
}

#9


2  

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

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

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

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

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

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

#10


2  

You can follow this path as a css solution

您可以按照这个路径作为css解决方案

img {
        width:200px;
        height:200px;
        position:relative
   }
img:after {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: inherit;
        height: inherit;
        background: #ebebeb url('http://via.placeholder.com/300?text=PlaceHolder') no-repeat center;
        color: transparent;
    }
<img src="gdfgd.jpg">

#11


1  

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

#12


1  

For future googlers, in 2016 there is a browser safe pure CSS way of hiding empty images using the attribute selector:

对于未来的谷歌人来说,2016年有一种浏览器安全的纯CSS方式,使用属性选择器隐藏空图片:

img[src="Error.src"] {
    display: none;
}

#13


-2  

A basic and very simple way of doing this without any code required would be to just provide an empty alt statement. The browser will then return the image as blank. It would look just like if the image isn't there.

一种基本且非常简单的方法,即不需要任何代码,只需提供一个空的alt语句。然后浏览器会将图像返回为空。它看起来就像如果图像不在那里。

Example:

例子:

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

Try it out to see! ;)

试试看!,)

#1


185  

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

For a CSS option see michalzuber's answer below. You can't hide the entire image, but you change how the broken icon looks.

有关CSS选项,请参阅下面的michalzuber的答案。你无法隐藏整个图像,但你可以改变坏掉的图标的样子。

#2


100  

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, ZERO people used something worse than IE8, meaning this solution works for literally everything).

这也适用于所有的浏览器,甚至可以追溯到IE8(在我2015年9月主持的网站的25万+访问者中,没有人使用比IE8更糟糕的东西,这意味着这个解决方案适用于所有东西)。

Step 1: Reference the image as an object instead 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开始,您可以交换地使用对象和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.

第二步:(可选,但很棒)在该对象中插入一个默认图像。如果要在对象中实际加载图像,则默认图像不会显示。例如,你可以显示一个用户头像列表,如果有人在服务器上还没有图片,它可以显示占位符图片……完全不需要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://*.com/a/32928240/3196360

…只需从这个答案中添加CSS—> https://*.com/a/32928240/3196360

#3


40  

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

#4


12  

I liked the answer by Nick and 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.

我很喜欢尼克的回答,并且在玩这个解决方案。发现了一个更清洁的方法。因为:before/::在pseudo之后不能处理替换的元素(如img和object),它们只在没有加载对象数据(src)时才能工作。它使HTML更简洁,并且只有在对象无法加载时才会添加pseudo。

http://codepen.io/anon/pen/xwqJKQ

http://codepen.io/anon/pen/xwqJKQ

<object data="http://lorempixel.com/200/200/people/1" type="image/png"></object>

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

object {
  position: relative;
  float: left;
  display: block;
  width: 200px;
  height: 200px;
  margin-right: 20px;
  border: 1px solid black;

  &::after {
    position: absolute;
    top: 0;
    left: 0;
    display: block;
    width: 100%;
    height: 100%;
    content: '';
    background: red url('http://placehold.it/200x200');
  }
}

#5


9  

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

我认为最简单的方法是将损坏的图像图标隐藏在文本缩进的属性中。

img {
    text-indent: -10000px
}

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

遗忘的是,如果你想看到alt属性,它就不能工作。

#6


8  

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

使用CSS非常困难,但是您可以使用CSS的背景图像而不是如何仅使用CSS/HTML(不使用js)隐藏图像破损图标标签…

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: http://jsfiddle.net/xbK6g/

这里有一个工作小提琴:http://jsfiddle.net/xbK6g/

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

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

#7


5  

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 = "动态图像" src = "数据:图像/ 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的src是空的,因此损坏的图像图标仍然出现在使用它的浏览器中。

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

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

#8


3  

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;
}

#9


2  

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

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

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

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

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

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

#10


2  

You can follow this path as a css solution

您可以按照这个路径作为css解决方案

img {
        width:200px;
        height:200px;
        position:relative
   }
img:after {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: inherit;
        height: inherit;
        background: #ebebeb url('http://via.placeholder.com/300?text=PlaceHolder') no-repeat center;
        color: transparent;
    }
<img src="gdfgd.jpg">

#11


1  

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

#12


1  

For future googlers, in 2016 there is a browser safe pure CSS way of hiding empty images using the attribute selector:

对于未来的谷歌人来说,2016年有一种浏览器安全的纯CSS方式,使用属性选择器隐藏空图片:

img[src="Error.src"] {
    display: none;
}

#13


-2  

A basic and very simple way of doing this without any code required would be to just provide an empty alt statement. The browser will then return the image as blank. It would look just like if the image isn't there.

一种基本且非常简单的方法,即不需要任何代码,只需提供一个空的alt语句。然后浏览器会将图像返回为空。它看起来就像如果图像不在那里。

Example:

例子:

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

Try it out to see! ;)

试试看!,)