如何仅使用CSS/HTML隐藏损坏的图像图标? [英] How to hide image broken Icon using only CSS/HTML?

查看:138
本文介绍了如何仅使用CSS/HTML隐藏损坏的图像图标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何隐藏残破的图像图标? 示例:

How can I hide the broken image icon? Example:

我有一个错误src的图像:

I have an image with error src:

<img src="Error.src"/>

该解决方案必须在所有浏览器中均可使用.

The solution must work in all browsers.

推荐答案

CSS/HTML无法知道图像是否损坏,因此无论如何都必须使用JavaScript

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

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

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

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

有关 CSS选项,请参见下面的 michalzuber的答案.您无法隐藏整个图像,但是可以更改损坏的图标的外观.

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/HTML隐藏损坏的图像图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆