用html、css、js 代码实现下列功能:有多张图片要加载。每张图片没加载完成时展示各自的loading字样,当各自的图片加载完成时,loading去除
时间: 2024-02-21 16:57:57 浏览: 13
可以使用以下代码实现:
HTML:
```
<div class="image-container">
<div class="image-wrapper">
<img class="image" src="image1.jpg" alt="Image 1">
<div class="loading">Loading...</div> <!-- Image 1 Loading 提示 -->
</div>
<div class="image-wrapper">
<img class="image" src="image2.jpg" alt="Image 2">
<div class="loading">Loading...</div> <!-- Image 2 Loading 提示 -->
</div>
<div class="image-wrapper">
<img class="image" src="image3.jpg" alt="Image 3">
<div class="loading">Loading...</div> <!-- Image 3 Loading 提示 -->
</div>
</div>
```
CSS:
```
.image-container {
display: flex;
flex-wrap: wrap;
}
.image-wrapper {
position: relative; /* 相对定位 */
width: 33.33%;
margin-bottom: 10px;
}
.loading {
position: absolute; /* 绝对定位 */
top: 50%; /* 垂直居中 */
left: 50%; /* 水平居中 */
transform: translate(-50%, -50%); /* 居中 */
z-index: 1; /* 显示在图片之上 */
display: none; /* 默认不显示 */
}
```
JS:
```
const images = document.querySelectorAll('.image');
images.forEach((image) => {
const imageWrapper = image.parentNode;
const loading = imageWrapper.querySelector('.loading');
image.addEventListener('load', () => {
image.style.display = 'block'; // 显示图片
loading.style.display = 'none'; // 隐藏 Loading 提示
});
image.addEventListener('error', () => {
image.style.display = 'none'; // 图片加载失败时隐藏图片
loading.style.display = 'none'; // 隐藏 Loading 提示
});
if (!image.complete) { // 图片未加载完成
image.style.display = 'none'; // 隐藏图片
loading.style.display = 'block'; // 显示 Loading 提示
}
});
```
这样当页面加载时,会显示各自的 Loading 提示,当各自的图片加载完成后,Loading 提示会被隐藏。同时,当图片加载失败时,会隐藏图片和 Loading 提示。