问题描述
如何隐藏损坏的图像图标?示例:
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 隐藏图像损坏的图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!