三个怎么够,我也小试了一下
[HTML] 纯文本查看 复制代码 <html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.container {
padding-top: 20px;
}
.image-container {
padding: 20px;
overflow: hidden;
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 20px;
justify-items: center;
}
.image-container img {
width: 100%;
aspect-ratio:1;
}
</style>
</head>
<body>
<div class="container" id="container">
<div style="text-align: center">
<span>请输入获取图片数量:</span><input type="text" id="input" value="20">
<button onclick="fetchImgAsCount()">点击获取</button>
</div>
<div class="image-container" id="image-container"></div>
</div>
<script>
const container = document.getElementById("image-container");
const input = document.getElementById("input");
let arrayLoading = [];
const fetchImgUrl = (index) => {
arrayLoading[index] = false;
fetch("https://api.uomg.com/api/rand.img3?format=json")
.then((res) => res.json())
.then((res) => {
const { imgurl } = res;
const img = document.createElement("img");
img.src = imgurl;
container.appendChild(img);
arrayLoading[index] = true;
});
};
const fetchImgAsCount = () => {
if (!arrayLoading.every(i => i)) {
alert('再等等吧,还有请求未完成')
return
}
// 获取前移除所有的img
const imgs = document.getElementsByTagName("img")
Array.from(imgs).forEach(img => img.remove())
const count = Number(input.value);
if (!count) return;
arrayLoading = Array(count).fill(false);
Array(count).fill(null).forEach((_, index) => fetchImgUrl(index));
}
window.onload = fetchImgAsCount
</script>
</body>
</html>
|