如何静默隐藏“找不到图像"找不到 src 源图像时的图标 [英] How to silently hide "Image not found" icon when src source image is not found
问题描述
您是否知道如何在未找到图像文件时从呈现的 HTML 页面中隐藏经典的未找到图像"图标?
Do you know how to hide the classic "Image not found" icon from a rendered HTML page when an image file is not found?
任何使用 JavaScript/jQuery/CSS 的工作方法?
Any working method using JavaScript/jQuery/CSS?
推荐答案
您可以使用 JavaScript 中的 onerror
事件在图像加载失败时采取行动:
You can use the onerror
event in JavaScript to act when an image fails to load:
var img = document.getElementById("myImg");
img.onerror = function () {
this.style.display = "none";
}
在 jQuery 中(因为你问过):
In jQuery (since you asked):
$("#myImg").error(function () {
$(this).hide();
});
或者对于所有图像:
$("img").error(function () {
$(this).hide();
// or $(this).css({visibility:"hidden"});
});
如果隐藏图像可能会改变布局,您应该使用 visibility: hidden
而不是 .hide()
.网络上的许多网站都使用默认的无图像"图像,当指定的图像位置不可用时,将 src
属性指向该图像.
You should use visibility: hidden
instead of .hide()
if hiding the images might change the layout. Many sites on the web use a default "no image" image instead, pointing the src
attribute to that image when the specified image location is unavailable.
这篇关于如何静默隐藏“找不到图像"找不到 src 源图像时的图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!