如何静默隐藏“未找到图片”图标,当找不到src源图像 [英] How to silently hide "Image not found" icon when src source image is not found

查看:897
本文介绍了如何静默隐藏“未找到图片”图标,当找不到src源图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当找不到图片文件时,您是否知道如何隐藏已渲染的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?

推荐答案

可以使用 onerror 事件在JavaScript中,当图片无法加载时执行:

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屋!

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