// 全局变量 let allAlbums = []; // 存储所有相册数据 let displayedAlbums = []; // 当前显示的相册数据 let searchTimeout = null; let currentDisplayPage = 1; // 前端显示的分页 let albumsPerPage = 50; // 每次显示50个相册 let isLoadingMore = false; let hasMoreAlbums = true; let lazyLoadObserver = null; let isAllAlbumsLoaded = false; // 标记是否已加载所有相册数据 let isInFavoritesPage = false; // 标记当前是否在收藏页 // API基础URL const API_BASE = '/api'; // 设备检测 const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0; // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', function () { // 添加设备类到body if (isMobile) { document.body.classList.add('mobile-device'); } if (isTouchDevice) { document.body.classList.add('touch-device'); } loadAlbums(); initSearch(); initInfiniteScroll(); }); // 初始化搜索功能 function initSearch() { const searchInput = document.getElementById('search-input'); // 防抖搜索 searchInput.addEventListener('input', function () { clearTimeout(searchTimeout); // 优化:根据输入长度动态调整延迟 const inputLength = this.value.length; const debounceDelay = inputLength > 3 ? 200 : 500; // 长文本快速搜索,短文本慢速搜索 searchTimeout = setTimeout(debouncedSearch, debounceDelay); }); // 移动端优化:搜索框聚焦时自动滚动到可视区域 if (isMobile) { searchInput.addEventListener('focus', function () { setTimeout(() => { searchInput.scrollIntoView({behavior: 'smooth', block: 'center'}); }, 100); }); } } // 初始化无限滚动 function initInfiniteScroll() { let scrollTimeout; window.addEventListener('scroll', function () { clearTimeout(scrollTimeout); scrollTimeout = setTimeout(handleScroll, 100); }); } // 处理滚动事件 function handleScroll() { // 如果在收藏页,禁用无限滚动 if (isInFavoritesPage) return; if (isLoadingMore || !hasMoreAlbums) return; // 检查是否滚动到底部 const scrollTop = window.scrollY || document.documentElement.scrollTop; const scrollHeight = document.documentElement.scrollHeight; const clientHeight = window.innerHeight; // 当距离底部还有200px时开始加载 if (scrollTop + clientHeight >= scrollHeight - 200) { loadMoreAlbums(); } } // 加载更多相册(从前端已加载的数据中获取) async function loadMoreAlbums() { // 如果在收藏页,不加载更多数据 if (isInFavoritesPage) return; if (isLoadingMore || !hasMoreAlbums || !isAllAlbumsLoaded) return; isLoadingMore = true; try { // 显示加载更多指示器 showLoadingMore(); // 增加当前显示页数 currentDisplayPage++; // 显示下一页数据 displayCurrentPage(); // 初始化图片懒加载 initLazyLoading(); // 预加载下一批图片 preloadNextBatchImages(); } catch (error) { console.error('加载更多相册失败:', error); showLoadMoreError(); } finally { isLoadingMore = false; hideLoadingMore(); } } // 显示加载更多错误 function showLoadMoreError() { const container = document.getElementById('albums-container'); const errorElement = document.createElement('div'); errorElement.className = 'load-more-error'; errorElement.innerHTML = `
${message}
尝试:
快去收藏一些喜欢的图片吧!
共收藏了 ${favoriteImages.length} 张图片