// 全局变量 let allAlbums = []; let searchTimeout = null; let currentPage = 1; let albumsPerPage = 50; // 减少每页数量,提高加载速度 let isLoadingMore = false; let hasMoreAlbums = true; let lazyLoadObserver = null; // 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 (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 (isLoadingMore || !hasMoreAlbums) return; isLoadingMore = true; try { await loadAlbums(); } catch (error) { console.error('加载更多相册失败:', error); showLoadMoreError(); } finally { isLoadingMore = false; } } // 显示加载更多错误 function showLoadMoreError() { const container = document.getElementById('albums-container'); const errorElement = document.createElement('div'); errorElement.className = 'load-more-error'; errorElement.innerHTML = `
${message}
尝试:
快去收藏一些喜欢的图片吧!
共收藏了 ${favoriteImages.length} 张图片