当没有找到源图像时,如何隐藏 Image Not Found 图标
JavaScript和jQuery可以用来隐藏“Image Not Found “图标,当图像没有找到时。其基本思路是,当出现错误时,将图像对象的显示属性设置为‘隐藏’让我们来看看下面的HTML代码,它显示了GeeksforGeeks的标志,作为示范。
例子:在这个例子中,我们不会隐藏未找到的图像的图标。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>
Example to hide the 'Image Not Found' icon i.e.
<img src="error.png" width="20px" />
</h2>
<img id="HideImg" src="geeksforgeeks-6.png" />
</body>
</html>
输出:
- 当图像可用时。
- 没有找到图像时。
隐藏图像错误图标的方法:
- 使用onerror()事件。当相应的项目出现错误时,会自动调用onerror事件。当图片没有找到时,onerror事件同时调用hideImg()函数,将图片的可见度设置为隐藏。
代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>
Example to hide the 'Image Not Found' icon i.e.
<img src="error.png" width="20px" />
</h2>
<img id="HideImg" src="geeksforgeeks-6.png"
onerror="hideImg()"/>
<script>
function hideImg() {
document.getElementById("HideImg")
.style.display = "none";
}
</script>
</body>
</html>
- 使用简短的记号。你可以对HTML事件应用这个简短的记号。这将把引用对象的可见性设置为隐藏。
代码:
<html>
<head>
</head>
<body>
<h2>
Example to hide the 'Image Not Found' icon i.e.
<img src="error.png" width="20px" />
</h2>
<img id="HideImg" src="geeksforgeeks-6.png"
onerror='this.style.display = "none"' />
</body>
</html>
- 使用jQuery。使用JQuery的错误处理函数error(),我们可以捕捉到错误并使用hide()函数隐藏对象。
注意: error()函数已从jquery 3.0.及以后的版本中删除。
Program:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
</script>
</head>
<body>
<h2>
Example to hide the 'Image Not Found' icon i.e.
<img src="error.png" width="20px" />
</h2>
<img id="HideImg" src="geeksforgeeks-6.png" />
</body>
</html>
<script>
(document).ready(function () {
("#HideImg").error(function () {
$(this).hide();
});
});
</script>
输出:上述所有代码都给出了相同的输出。