如何检查图像是否已加载?
概述
为了执行某些操作,可以使用 JavaScript 检查图像是否已加载。在很多情况下,由于图像尺寸过大或网络连接不佳,浏览器无法加载图像。因此,我们的图像有时可能会显示某些错误。因此,为了知道我们的图像是否已加载,我们有一些方法,例如 onload()、onerror() 和 complete 属性。
语法
解决此问题的语法如下:
onload="function()" - 当图像成功加载时,将调用此函数。在此,传递任何回调函数以执行特定操作。
onerror="function()" - 当图像由于任何原因在加载过程中遇到问题时,此函数将触发。
selector.complete - selector.complete 方法使用类名、ID 或标签名称选择图像,然后检查图像是否已完全加载。
要检查已加载的图像,我们有两种方法
方法 1 - 在这种方法中,我们将使用两种方法 onload() 和 onerror()。在这两种方法中,将传递一个函数作为参数,该函数将在浏览器加载时被调用,并检查图像是否已加载。
算法
步骤 1 - 在 HTML 中创建一个图像标签,并在 src 属性中插入图像的链接或路径 <image src= “在此处放置您的链接”/>。
步骤 2 - 访问图像标签并将其存储在变量中。
步骤 3 - 在 addEventListener() 中使用 load() 方法和 error() 方法。
步骤 4 - 如果在浏览器加载时图像成功加载,则 load 事件将触发并返回特定操作,否则如果图像无法加载,则 error 事件将触发。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<title>Check whether image is loaded or not</title>
<style>
body{
min-height: 90vh;
display: flex;
flex-direction: column;
place-content: center;
background-color: #0a0a0a;
color: white;
text-align: center;
}
img{
width: 50%;
height: 70%;
border-radius: 8px;
margin: auto auto ;
box-shadow: 0 0 8px white;
}
</style>
</head>
<body>
<img src= "https://tutorialspoint.com/images/logo.png" id="sample" onload="checkLoad()" onerror="checkError()" alt="error">
<h2 id="output"></h2>
<script>
document.getElementById("sample").addEventListener("load", () => {
document.getElementById("output").innerText="Image Loaded Sucessfully";
})
document.getElementById("sample").addEventListener("error", () => {
document.getElementById("output").innerText="Error occured while loading image!";
})
</script>
</body>
</html>
在网页浏览器上加载图像时没有错误。因此,在示例中,addEventListener() 中的 load() 方法将触发输出“图像已成功加载”。
方法 2 - 在这种方法中,我们调用图像对象的 complete() 方法,该方法检查图像是否已完全加载,并据此返回 true 或 false。当图像在加载过程中遇到任何问题时,它将返回 false,否则返回 true。
算法
步骤 1 - 在 HTML 中创建一个图像标签,并在 src 属性中插入图像的链接或路径 <image src= “在此处放置您的链接”/>。
步骤 2 - 访问图像标签并将其存储在变量中。
步骤 3 - 使用图像对象的 complete() 方法。如果图像已在浏览器中加载,它将在浏览器上提醒 true,否则它将在浏览器上提醒 false。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<title>Check whether image is loaded or not</title>
<style>
body{
min-height: 90vh;
display: flex;
flex-direction: column;
place-content: center;
background-color: #0a0a0a;
color: white;
text-align: center;
}
img{
width: 50%;
height: 70%;
border-radius: 8px;
margin: auto auto ;
box-shadow: 0 0 8px white;
}
</style>
</head>
<body>
<img src= "https://tutorialspoint.com/images/logo.png" id="sample" onload="checkLoad()" onerror="checkError()" alt="error">
<h2 id="output"></h2>
<script>
var i = document.getElementById("sample");
var load = i.complete;
alert(load);
</script>
</body>
</html>
以上代码显示了 complete() 方法返回 true 的输出。
结论
complete() 方法的返回类型是布尔值,因为它根据当前情况返回 true 或 false。在某些情况下图像无法加载,例如图像的 URL 错误、网络连接不良、图像不存在于指定目录中。以上解决方案在许多情况下都很有帮助,因为它在图像完全加载时触发特定操作。JavaScript 中的图像对象包含许多有助于在 DOM 中操作图像的方法。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP