无限加载页面
wptutor
2024-02-22
78 Views
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Infinite Scrolling Page with Grid Images</title>
<style>
/* Styles for the loading spinner */
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Style for the container to hold the grid */
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-gap: 20px;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
/* Style for the image */
.image {
width: 100%;
height: auto;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body>
<div class="container" id="container">
<!-- Images will be appended here -->
</div>
<!-- Loading spinner -->
<div class="loader" id="loader"></div>
<script>
let page = 1; // Initial page number
const perPage = 10; // Number of items per page
let isLoading = false; // Flag to prevent multiple simultaneous requests
// Function to fetch data from API
async function fetchData() {
try {
isLoading = true;
const response = await fetch(`https://jsonplaceholder.typicode.com/photos?_page=${page}&_limit=${perPage}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
} finally {
isLoading = false;
}
}
// Function to render data
function renderData(data) {
const container = document.getElementById('container');
data.forEach(item => {
const imageElement = document.createElement('img');
imageElement.classList.add('image');
imageElement.src = item.url;
imageElement.alt = item.title;
container.appendChild(imageElement);
});
}
// Function to handle scroll event
async function handleScroll() {
const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
if (scrollTop + clientHeight >= scrollHeight - 5 && !isLoading) {
page++;
const data = await fetchData();
renderData(data);
}
}
// Event listener for scroll
window.addEventListener('scroll', handleScroll);
// Initial data load 初始化data,也就是页面加载时候有10篇文章
fetchData().then(data => renderData(data));
</script>
</body>
</html>