如何隐藏图像破碎图标仅使用CSS / HTML(无js) [英] How to hide image broken Icon using only CSS/HTML (without js)
本文介绍了如何隐藏图像破碎图标仅使用CSS / HTML(无js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何隐藏已损坏的图片图示?
示例:
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而不是JS。
Using only CSS or HTML, not JS.
推荐答案
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 / HTML(无js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文