This commit is contained in:
lychang
2026-03-22 04:02:47 +08:00
parent e4bf7cf1a4
commit f3ae54a26b
22 changed files with 10607 additions and 347 deletions

View File

@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>相册详情 - 图片展示服务</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/font-awesome.css">
<link rel="stylesheet" href="/assets/css/style.css">
<link rel="stylesheet" href="/assets/css/album.css">
</head>
@@ -27,15 +27,55 @@
</div>
</div>
<!-- 图片查看器 -->
<div class="lightbox" id="lightbox">
<span class="lightbox-close" onclick="closeLightbox()">&times;</span>
<div class="lightbox-nav">
<button onclick="prevImage()"><i class="fas fa-chevron-left"></i></button>
<button onclick="nextImage()"><i class="fas fa-chevron-right"></i></button>
<!-- 图片查看器 - 使用previewModal相同逻辑 -->
<div class="preview-modal" id="lightbox">
<div class="preview-overlay" onclick="closeLightbox()"></div>
<div class="preview-container">
<div class="preview-header">
<div class="preview-title">
<h3 id="lightbox-title">图片标题</h3>
<span class="preview-info" id="lightbox-album">来自: 相册名称</span>
</div>
<div class="preview-actions">
<button class="preview-nav preview-prev" onclick="prevImage()" id="lightbox-prev">
<i class="fas fa-chevron-left"></i>
</button>
<span class="preview-counter" id="lightbox-counter">1 / 1</span>
<button class="preview-nav preview-next" onclick="nextImage()" id="lightbox-next">
<i class="fas fa-chevron-right"></i>
</button>
<button class="preview-close" onclick="closeLightbox()">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="preview-content">
<div class="preview-image-container">
<img id="lightbox-img" src="" alt="" class="preview-image" loading="eager">
<div class="preview-loading">
<i class="fas fa-spinner fa-spin"></i>
<span>加载中...</span>
</div>
</div>
</div>
<div class="preview-footer">
<div class="preview-meta">
<span class="meta-item" id="lightbox-dimensions">
<i class="fas fa-ruler-combined"></i>
0 × 0
</span>
<span class="meta-item" id="lightbox-size">
<i class="fas fa-weight-hanging"></i>
0 KB
</span>
</div>
<div class="preview-controls">
<button class="preview-action" onclick="addToFavoritesFromLightbox()" id="lightbox-favorite-btn">
<i class="fas fa-heart"></i> 加入收藏
</button>
</div>
</div>
</div>
<img id="lightbox-img" src="" alt="">
<div class="lightbox-info" id="lightbox-info"></div>
</div>
<script src="/assets/js/album.js"></script>

View File

@@ -1,4 +1,4 @@
/* 相册详情页面特定样式 - 蓝白配色体系 */
/* 相册详情页面特定样式 - 增强响应式支持 */
:root {
--primary-blue: #1e40af;
--secondary-blue: #3b82f6;
@@ -16,6 +16,8 @@
--shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.1);
--border-radius: 12px;
--border-radius-lg: 20px;
--mobile-breakpoint: 768px;
--tablet-breakpoint: 1024px;
}
body {
@@ -24,6 +26,7 @@ body {
min-height: 100vh;
color: var(--text-dark);
line-height: 1.6;
overflow-x: hidden;
}
.container {
@@ -80,12 +83,84 @@ body {
margin-right: auto;
}
/* 智能图片网格布局 - 自适应瀑布流效果 */
.images-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 25px;
margin-bottom: 50px;
align-items: start; /* 顶部对齐 */
}
/* 大屏幕下的优化布局 */
@media (min-width: 1200px) {
.images-grid {
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 30px;
}
}
/* 宽幅图片布局 - 超宽图片 (ratio > 1.5) */
.image-item.landscape {
grid-column: span 1;
}
.image-item.landscape img {
aspect-ratio: 16/9;
height: auto;
width: 100%;
object-fit: cover;
}
/* 竖幅图片布局 - 超高图片 (ratio < 0.67) */
.image-item.portrait {
grid-column: span 1;
}
.image-item.portrait img {
aspect-ratio: 3/4;
height: auto;
width: 100%;
object-fit: cover;
}
/* 较宽图片布局 (1.2 < ratio ≤ 1.5) */
.image-item.wide {
grid-column: span 1;
}
.image-item.wide img {
aspect-ratio: 4/3;
height: auto;
width: 100%;
object-fit: cover;
}
/* 较高图片布局 (0.83 ≤ ratio < 1.2) */
.image-item.tall {
grid-column: span 1;
}
.image-item.tall img {
aspect-ratio: 3/4;
height: auto;
width: 100%;
object-fit: cover;
}
/* 方形图片布局 (接近1:1) */
.image-item.square {
grid-column: span 1;
}
.image-item.square img {
aspect-ratio: 1/1;
height: auto;
width: 100%;
object-fit: cover;
}
/* 默认图片样式(未分类的图片) */
.image-item {
position: relative;
overflow: hidden;
@@ -96,18 +171,22 @@ body {
cursor: pointer;
border: 1px solid var(--medium-gray);
}
.image-item:hover {
transform: translateY(-8px);
box-shadow: var(--shadow-xl);
border-color: var(--accent-blue);
}
/* 通用图片样式 - 移除固定高度,使用自适应 */
.image-item img {
width: 100%;
height: 220px;
height: auto; /* 改为自适应高度 */
object-fit: cover;
display: block;
transition: transform 0.5s ease;
}
.image-item:hover img {
transform: scale(1.05);
}
@@ -118,6 +197,100 @@ body {
font-size: 0.9rem;
font-weight: 500;
line-height: 1.4;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.image-caption small {
background: var(--light-gray);
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8rem;
color: var(--text-light);
}
/* 收藏按钮样式 */
.favorite-btn {
position: absolute;
top: 10px;
right: 10px;
background: rgba(255, 255, 255, 0.9);
border: none;
border-radius: 50%;
width: 36px;
height: 36px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
backdrop-filter: blur(10px);
box-shadow: var(--shadow-sm);
opacity: 0;
z-index: 10;
}
.image-item:hover .favorite-btn {
opacity: 1;
}
.favorite-btn:hover {
background: rgba(255, 255, 255, 1);
transform: scale(1.1);
box-shadow: var(--shadow-md);
}
.favorite-btn.favorited {
color: #ec4899;
background: rgba(236, 72, 153, 0.1);
}
.favorite-btn.favorited:hover {
background: rgba(236, 72, 153, 0.2);
}
.favorite-btn i {
font-size: 16px;
transition: all 0.3s ease;
}
/* 触摸设备显示收藏按钮 */
@media (hover: none) and (pointer: coarse) {
.favorite-btn {
opacity: 0.7;
}
.image-item:active .favorite-btn {
opacity: 1;
transform: scale(1.1);
}
}
/* 图片加载状态 */
.image-loading {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: var(--light-gray);
display: flex;
align-items: center;
justify-content: center;
color: var(--text-light);
}
.image-loading .fa-spinner {
font-size: 1.5rem;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 图片查看器样式 */
@@ -199,6 +372,294 @@ body {
padding: 15px 25px;
border-radius: var(--border-radius);
backdrop-filter: blur(10px);
max-width: 80%;
}
/* 响应式媒体查询 - 移动端优化 */
@media (max-width: 1024px) {
.container {
padding: 25px 15px;
}
.header {
margin-bottom: 35px;
}
.album-title {
font-size: 2.2rem;
}
.album-info {
font-size: 1.1rem;
padding: 18px;
margin-bottom: 35px;
}
.images-grid {
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
}
.image-item img {
height: auto; /* 自适应高度 */
}
.lightbox img {
max-width: 90%;
max-height: 70%;
}
.lightbox-close {
top: 20px;
right: 25px;
font-size: 30px;
width: 45px;
height: 45px;
}
}
@media (max-width: 768px) {
.container {
padding: 20px 15px;
}
.header {
margin-bottom: 30px;
}
.back-link {
padding: 10px 20px;
font-size: 0.9rem;
margin-bottom: 20px;
}
.album-title {
font-size: 1.8rem;
margin-bottom: 12px;
}
.album-info {
font-size: 1rem;
padding: 15px;
margin-bottom: 30px;
}
.images-grid {
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 15px;
}
.image-item {
border-radius: 10px;
}
.image-item img {
height: auto; /* 自适应高度 */
}
.image-caption {
padding: 10px;
font-size: 0.85rem;
}
.image-caption small {
font-size: 0.75rem;
padding: 3px 6px;
}
.lightbox {
padding: 20px;
}
.lightbox img {
max-width: 95%;
max-height: 65%;
}
.lightbox-close {
top: 15px;
right: 15px;
font-size: 24px;
width: 40px;
height: 40px;
}
.lightbox-nav {
padding: 0 10px;
}
.lightbox-nav button {
font-size: 24px;
padding: 10px 20px;
}
.lightbox-info {
font-size: 1rem;
padding: 12px 20px;
margin-top: 20px;
}
}
@media (max-width: 480px) {
.container {
padding: 15px 10px;
}
.header {
margin-bottom: 25px;
}
.back-link {
padding: 8px 16px;
font-size: 0.85rem;
margin-bottom: 15px;
}
.album-title {
font-size: 1.6rem;
margin-bottom: 10px;
}
.album-info {
font-size: 0.9rem;
padding: 12px;
margin-bottom: 25px;
}
.images-grid {
grid-template-columns: 1fr;
gap: 12px;
}
.image-item img {
height: auto; /* 自适应高度 */
}
.image-caption {
padding: 8px;
font-size: 0.8rem;
flex-direction: column;
align-items: flex-start;
gap: 6px;
}
.lightbox {
padding: 15px;
}
.lightbox img {
max-width: 100%;
max-height: 60%;
}
.lightbox-close {
top: 10px;
right: 10px;
font-size: 20px;
width: 35px;
height: 35px;
}
.lightbox-nav {
padding: 0 5px;
}
.lightbox-nav button {
font-size: 20px;
padding: 8px 16px;
}
.lightbox-info {
font-size: 0.9rem;
padding: 10px 15px;
margin-top: 15px;
max-width: 95%;
}
}
/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
.image-item:hover {
transform: none;
box-shadow: var(--shadow-lg);
}
.image-item:active {
transform: scale(0.98);
box-shadow: var(--shadow-md);
}
.back-link:hover {
transform: none;
}
.back-link:active {
transform: scale(0.95);
}
.lightbox-nav button:hover {
transform: none;
}
.lightbox-nav button:active {
transform: scale(0.9);
}
.lightbox-close:hover {
transform: none;
}
.lightbox-close:active {
transform: scale(0.9);
}
}
/* 横屏模式优化 */
@media (orientation: landscape) and (max-height: 500px) {
.lightbox {
flex-direction: row;
align-items: center;
}
.lightbox img {
max-width: 70%;
max-height: 85%;
}
.lightbox-info {
margin-top: 0;
margin-left: 20px;
max-width: 25%;
}
}
/* 高分辨率屏幕优化 */
@media (min-resolution: 2dppx) {
.image-item img {
image-rendering: -webkit-optimize-contrast;
image-rendering: crisp-edges;
}
.lightbox img {
image-rendering: auto;
}
}
/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
:root {
--primary-blue: #3b82f6;
--light-blue: #1e293b;
--white: #0f172a;
--light-gray: #334155;
--medium-gray: #475569;
--text-dark: #f1f5f9;
--text-light: #cbd5e1;
}
body {
background: linear-gradient(135deg, var(--light-blue) 0%, var(--white) 100%);
}
}
@media (max-width: 768px) {

7053
assets/css/font-awesome.css vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>流云图库</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/font-awesome.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body>
@@ -19,6 +19,15 @@
<label for="search-input"></label><input type="text" id="search-input" placeholder="搜索图片标题..." onkeypress="handleKeyPress(event)">
<button onclick="searchAlbums()"><i class="fas fa-search"></i></button>
</div>
<div class="action-buttons">
<button class="random-button" onclick="openRandomAlbum()">
<i class="fas fa-random"></i> 随机相册
</button>
<button class="favorites-button" onclick="showFavorites()">
<i class="fas fa-heart"></i> 收藏夹
</button>
</div>
</div>
<div class="stats" id="stats">

View File

@@ -3,8 +3,23 @@ let currentAlbum = null;
let currentImageIndex = 0;
let images = [];
// 设备检测
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
// API基础URL
const API_BASE = '/api';
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 添加设备类到body
if (isMobile) {
document.body.classList.add('mobile-device');
}
if (isTouchDevice) {
document.body.classList.add('touch-device');
}
const urlParams = new URLSearchParams(window.location.search);
const albumId = urlParams.get('id');
@@ -13,11 +28,32 @@ document.addEventListener('DOMContentLoaded', function() {
} else {
showError('缺少相册ID参数');
}
// 初始化键盘导航和触摸手势
initLightboxControls();
});
// 显示图片骨架屏
function showImageSkeleton(count = 8) {
const container = document.getElementById('images-container');
container.innerHTML = Array(count).fill(0).map(() => `
<div class="image-item">
<div class="image-loading">
<i class="fas fa-spinner"></i>
</div>
<div class="image-caption">
<small>加载中...</small>
</div>
</div>
`).join('');
}
// 加载相册详情
async function loadAlbum(albumId) {
try {
// 显示骨架屏
showImageSkeleton();
const response = await fetch(`/api/album/${albumId}`);
if (!response.ok) {
if (response.status === 404) {
@@ -32,6 +68,9 @@ async function loadAlbum(albumId) {
updateAlbumInfo();
displayImages();
// 初始化图片懒加载
initLazyLoading();
} catch (error) {
console.error('加载相册失败:', error);
showError('加载相册失败: ' + error.message);
@@ -46,6 +85,21 @@ function updateAlbumInfo() {
document.title = `${currentAlbum.title} - 图片展示服务`;
}
// 智能判断图片方向 - 更精确的判断逻辑
function getImageOrientation(width, height) {
if (!width || !height) return 'square';
const ratio = width / height;
// 更精确的阈值判断
if (ratio > 1.5) return 'landscape'; // 宽幅图片
if (ratio < 0.67) return 'portrait'; // 竖幅图片
if (ratio > 1.2) return 'wide'; // 较宽图片
if (ratio < 0.83) return 'tall'; // 较高图片
return 'square'; // 方形或接近方形的图片
}
// 显示图片列表
function displayImages() {
const container = document.getElementById('images-container');
@@ -56,121 +110,358 @@ function displayImages() {
}
container.innerHTML = images.map((image, index) => {
// 优先使用缩略图API,如果没有则使用原始URL
// 智能判断图片方向
const orientation = getImageOrientation(image.width, image.height);
// 使用懒加载技术
let imageUrl = '/assets/placeholder.svg';
let dataSrc = '';
if (image.id) {
imageUrl = `/api/thumbnail/${image.id}`;
dataSrc = `/api/thumbnail/${image.id}`;
imageUrl = '/assets/placeholder.svg'; // 初始使用占位图
} else if (image.original_url) {
imageUrl = image.original_url;
dataSrc = image.original_url;
imageUrl = '/assets/placeholder.svg';
}
const title = image.title || `图片 ${index + 1}`;
// 检查图片是否已被收藏
const isFavorited = isImageFavorited(image.id || image.original_url);
return `
<div class="image-item" onclick="openLightbox(${index})">
<img src="${imageUrl}" alt="${title}" onerror="this.src='/assets/placeholder.svg'">
<div class="image-item ${orientation}" onclick="openLightbox(${index})">
<img
src="${imageUrl}"
${dataSrc ? `data-src="${dataSrc}"` : ''}
alt="${title}"
class="lazy"
onerror="this.src='/assets/placeholder.svg'"
>
<div class="image-caption">
${image.width ? `<small>${image.width}×${image.height}</small>` : ''}
${image.file_size ? `<small>${(image.file_size / 1024 ).toFixed(2)} KB</small>` : ''}
${image.file_size ? `<small>${(image.file_size / 1024).toFixed(2)} KB</small>` : ''}
</div>
</div>
`;
}).join('');
}
// 打开图片查看器
// 打开图片查看器 - 使用previewModal相同逻辑
function openLightbox(index) {
currentImageIndex = index;
const lightbox = document.getElementById('lightbox');
const lightboxImg = document.getElementById('lightbox-img');
const lightboxInfo = document.getElementById('lightbox-info');
const image = images[index];
// 在lightbox中优先使用原始图片以获得更好的显示效果
let imageUrl = '/assets/placeholder.svg';
if (image.id) {
imageUrl = `/api/original/${image.id}`;
} else if (image.original_url) {
imageUrl = image.original_url;
}
// 更新lightbox内容
updateLightboxContent(index);
lightboxImg.src = imageUrl;
const title = image.title || `图片 ${index + 1}`;
let infoText = `${title} (${index + 1}/${images.length})`;
if (image.width && image.height) {
infoText += ` | ${image.width}×${image.height}`;
}
if (image.file_size) {
infoText += ` | ${(image.file_size / 1024 ).toFixed(2)} KB`;
}
lightboxInfo.textContent = infoText;
lightbox.style.display = 'flex';
// 显示lightbox
lightbox.classList.add('active');
document.body.style.overflow = 'hidden';
}
// 关闭图片查看器
function closeLightbox() {
const lightbox = document.getElementById('lightbox');
lightbox.style.display = 'none';
lightbox.classList.remove('active');
document.body.style.overflow = 'auto';
}
// 下一张图片
function nextImage() {
currentImageIndex = (currentImageIndex + 1) % images.length;
updateLightboxImage();
const newIndex = (currentImageIndex + 1) % images.length;
updateLightboxContent(newIndex);
}
// 上一张图片
function prevImage() {
currentImageIndex = (currentImageIndex - 1 + images.length) % images.length;
updateLightboxImage();
const newIndex = (currentImageIndex - 1 + images.length) % images.length;
updateLightboxContent(newIndex);
}
// 更新图片查看器显示
function updateLightboxImage() {
const lightboxImg = document.getElementById('lightbox-img');
const lightboxInfo = document.getElementById('lightbox-info');
// 更新lightbox内容(不关闭面板)
function updateLightboxContent(newIndex) {
currentImageIndex = newIndex;
const image = images[newIndex];
// 更新标题和相册信息
const titleElement = document.getElementById('lightbox-title');
const albumElement = document.getElementById('lightbox-album');
if (titleElement) titleElement.textContent = image.title || `图片 ${newIndex + 1}`;
if (albumElement) albumElement.textContent = `来自: ${currentAlbum.title}`;
// 更新计数器
const counterElement = document.getElementById('lightbox-counter');
if (counterElement) counterElement.textContent = `${newIndex + 1} / ${images.length}`;
// 更新导航按钮状态
const prevButton = document.getElementById('lightbox-prev');
const nextButton = document.getElementById('lightbox-next');
if (prevButton) prevButton.disabled = newIndex === 0;
if (nextButton) nextButton.disabled = newIndex === images.length - 1;
// 检查收藏状态
checkLightboxFavoriteStatus();
// 更新元数据
const dimensionsElement = document.getElementById('lightbox-dimensions');
const sizeElement = document.getElementById('lightbox-size');
if (dimensionsElement) {
dimensionsElement.innerHTML = `<i class="fas fa-ruler-combined"></i> ${image.width || 0} × ${image.height || 0}`;
}
if (sizeElement) {
const fileSizeKB = image.file_size ? (image.file_size / 1024).toFixed(2) : '0';
sizeElement.innerHTML = `<i class="fas fa-weight-hanging"></i> ${fileSizeKB} KB`;
}
// 更新图片
const imageElement = document.getElementById('lightbox-img');
const loadingElement = document.querySelector('#lightbox .preview-loading');
if (imageElement && loadingElement) {
// 显示加载状态
imageElement.style.opacity = '0';
loadingElement.style.display = 'flex';
// 加载新图片
const newImage = new Image();
// 在lightbox中优先使用原始图片以获得更好的显示效果
let imageUrl = '/assets/placeholder.svg';
if (image.id) {
imageUrl = `/api/original/${image.id}`;
} else if (image.original_url) {
imageUrl = image.original_url;
}
newImage.src = imageUrl;
newImage.alt = image.title || `图片 ${newIndex + 1}`;
newImage.className = 'preview-image';
newImage.onload = function() {
// 替换图片
if (imageElement.parentNode) {
imageElement.parentNode.replaceChild(newImage, imageElement);
// 重新设置ID
newImage.id = 'lightbox-img';
}
// 隐藏加载状态
loadingElement.style.display = 'none';
newImage.style.opacity = '1';
};
newImage.onerror = function() {
// 图片加载失败
loadingElement.innerHTML = '<i class="fas fa-exclamation-triangle"></i><span>图片加载失败</span>';
};
}
}
// 初始化图片懒加载
function initLazyLoading() {
if ('IntersectionObserver' in window) {
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy');
delete img.dataset.src;
}
imageObserver.unobserve(img);
}
});
}, {
rootMargin: '50px 0px',
threshold: 0.1
});
document.querySelectorAll('img.lazy').forEach(img => {
imageObserver.observe(img);
});
} else {
// 不支持IntersectionObserver的浏览器回退方案
document.querySelectorAll('img.lazy').forEach(img => {
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy');
delete img.dataset.src;
}
});
}
}
// 初始化lightbox控制
function initLightboxControls() {
// 键盘导航
document.addEventListener('keydown', function(event) {
const lightbox = document.getElementById('lightbox');
if (lightbox.classList.contains('active')) {
switch(event.key) {
case 'Escape':
closeLightbox();
break;
case 'ArrowLeft':
prevImage();
break;
case 'ArrowRight':
nextImage();
break;
}
}
});
// 点击背景关闭
document.getElementById('lightbox').addEventListener('click', function(event) {
if (event.target === this) closeLightbox();
});
// 触摸手势支持
if (isTouchDevice) {
let touchStartX = 0;
let touchStartY = 0;
document.addEventListener('touchstart', function(event) {
touchStartX = event.touches[0].clientX;
touchStartY = event.touches[0].clientY;
});
document.addEventListener('touchend', function(event) {
const lightbox = document.getElementById('lightbox');
if (!lightbox.classList.contains('active')) return;
const touchEndX = event.changedTouches[0].clientX;
const touchEndY = event.changedTouches[0].clientY;
const deltaX = touchEndX - touchStartX;
const deltaY = touchEndY - touchStartY;
// 水平滑动距离大于垂直滑动距离,且水平滑动距离足够大
if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
if (deltaX > 0) {
prevImage();
} else {
nextImage();
}
}
// 轻点关闭(如果移动距离很小)
if (Math.abs(deltaX) < 10 && Math.abs(deltaY) < 10) {
closeLightbox();
}
});
}
}
// 从lightbox添加收藏
function addToFavoritesFromLightbox() {
const image = images[currentImageIndex];
// 在lightbox中优先使用原始图片以获得更好的显示效果
let imageUrl = '/assets/placeholder.svg';
if (image.id) {
imageUrl = `/api/original/${image.id}`;
} else if (image.original_url) {
imageUrl = image.original_url;
const imageId = image.id;
if (!imageId) {
alert('无法收藏此图片:缺少图片ID');
return;
}
lightboxImg.src = imageUrl;
const title = image.title || `图片 ${currentImageIndex + 1}`;
let infoText = `${title} (${currentImageIndex + 1}/${images.length})`;
if (image.width && image.height) {
infoText += ` | ${image.width}×${image.height}`;
}
if (image.file_size) {
infoText += ` | ${(image.file_size / 1024 ).toFixed(2)} KB`;
// 检查是否已经收藏
const favoriteBtn = document.getElementById('lightbox-favorite-btn');
if (favoriteBtn.classList.contains('favorited')) {
// 取消收藏
fetch(`${API_BASE}/favorites/image/${imageId}`, {
method: 'DELETE'
})
.then(response => {
if (!response.ok) {
throw new Error('取消收藏失败');
}
return response.json();
})
.then(() => {
favoriteBtn.classList.remove('favorited');
favoriteBtn.innerHTML = '<i class="fas fa-heart"></i> 加入收藏';
showFavoriteToast('已取消收藏', false);
})
.catch(error => {
console.error('取消收藏失败:', error);
alert('取消收藏失败,请稍后重试');
});
} else {
// 添加收藏
const favoriteData = {
image_id: imageId,
album_id: currentAlbum.id
};
fetch(`${API_BASE}/favorites`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(favoriteData)
})
.then(response => {
if (!response.ok) {
throw new Error('添加收藏失败');
}
return response.json();
})
.then(() => {
favoriteBtn.classList.add('favorited');
favoriteBtn.innerHTML = '<i class="fas fa-heart"></i> 已收藏';
showFavoriteToast('已添加到收藏夹', true);
})
.catch(error => {
console.error('添加收藏失败:', error);
alert('添加收藏失败,请稍后重试');
});
}
lightboxInfo.textContent = infoText;
// 添加动画效果
const heartIcon = favoriteBtn.querySelector('i');
if (heartIcon) {
heartIcon.style.transform = 'scale(1.3)';
setTimeout(() => {
heartIcon.style.transform = 'scale(1)';
}, 300);
}
}
// 键盘导航
document.addEventListener('keydown', function(event) {
const lightbox = document.getElementById('lightbox');
if (lightbox.style.display === 'flex') {
if (event.key === 'Escape') closeLightbox();
if (event.key === 'ArrowRight') nextImage();
if (event.key === 'ArrowLeft') prevImage();
}
});
// 点击背景关闭
document.getElementById('lightbox').addEventListener('click', function(event) {
if (event.target === this) closeLightbox();
});
// 检查图片收藏状态并更新lightbox按钮
function checkLightboxFavoriteStatus() {
const image = images[currentImageIndex];
const imageId = image.id;
const favoriteBtn = document.getElementById('lightbox-favorite-btn');
console.log(image)
if (!imageId || !favoriteBtn) return;
// 检查收藏状态
fetch(`${API_BASE}/favorites/status/${imageId}`)
.then(response => {
if (!response.ok) {
throw new Error('检查收藏状态失败');
}
return response.json();
})
.then(status => {
if (status.is_favorited) {
favoriteBtn.classList.add('favorited');
favoriteBtn.innerHTML = '<i class="fas fa-heart"></i> 已收藏';
} else {
favoriteBtn.classList.remove('favorited');
favoriteBtn.innerHTML = '<i class="fas fa-heart"></i> 加入收藏';
}
})
.catch(error => {
console.error('检查收藏状态失败:', error);
// 失败时默认显示"加入收藏"
favoriteBtn.classList.remove('favorited');
favoriteBtn.innerHTML = '<i class="fas fa-heart"></i> 加入收藏';
});
}
// 显示错误信息
function showError(message) {
@@ -179,4 +470,178 @@ function showError(message) {
document.getElementById('album-title').textContent = '加载失败';
document.getElementById('album-info').innerHTML = '';
}
}
// 移动端优化:防止双击缩放
function preventDoubleTapZoom() {
if (isTouchDevice) {
let lastTouchEnd = 0;
document.addEventListener('touchend', function(event) {
const now = (new Date()).getTime();
if (now - lastTouchEnd <= 300) {
event.preventDefault();
}
lastTouchEnd = now;
}, false);
}
}
// 性能监控
function logPerformance() {
if ('performance' in window) {
window.addEventListener('load', () => {
setTimeout(() => {
const navigationTiming = performance.getEntriesByType('navigation')[0];
console.log('相册页面加载时间:', navigationTiming.loadEventEnd - navigationTiming.navigationStart, 'ms');
}, 0);
});
}
}
// 检查图片是否已收藏
function isImageFavorited(imageId) {
// 这里需要从后端API获取收藏状态
// 暂时返回false,实际实现中需要调用API
return false;
}
// 切换收藏状态
function toggleFavorite(event, imageIndex) {
event.stopPropagation(); // 阻止事件冒泡,避免打开lightbox
const image = images[imageIndex];
const imageId = image.id;
if (!imageId) {
alert('无法收藏此图片:缺少图片ID');
return;
}
// 检查当前收藏状态
const isFavorited = event.target.classList.contains('favorited');
if (isFavorited) {
// 取消收藏
fetch(`${API_BASE}/favorites/image/${imageId}`, {
method: 'DELETE'
})
.then(response => {
if (!response.ok) {
throw new Error('取消收藏失败');
}
return response.json();
})
.then(() => {
event.target.classList.remove('favorited');
showFavoriteToast('已取消收藏', false);
})
.catch(error => {
console.error('取消收藏失败:', error);
alert('取消收藏失败,请稍后重试');
});
} else {
// 添加收藏
const favoriteData = {
image_id: imageId,
album_id: currentAlbum.id
};
fetch(`${API_BASE}/favorites`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(favoriteData)
})
.then(response => {
if (!response.ok) {
throw new Error('添加收藏失败');
}
return response.json();
})
.then(() => {
event.target.classList.add('favorited');
showFavoriteToast('已添加到收藏夹', true);
})
.catch(error => {
console.error('添加收藏失败:', error);
alert('添加收藏失败,请稍后重试');
});
}
// 添加动画效果
let heartIcon;
// 确保找到正确的图标元素
if (event.target.tagName === 'I') {
heartIcon = event.target;
} else if (event.target.tagName === 'BUTTON') {
heartIcon = event.target.querySelector('i');
} else {
heartIcon = event.target.closest('.favorite-btn')?.querySelector('i');
}
if (heartIcon) {
heartIcon.style.transform = 'scale(1.3)';
setTimeout(() => {
heartIcon.style.transform = 'scale(1)';
}, 300);
}
}
// 显示收藏提示
function showFavoriteToast(message, isAdd) {
// 创建提示元素
let toast = document.getElementById('favorite-toast');
if (!toast) {
toast = document.createElement('div');
toast.id = 'favorite-toast';
toast.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: ${isAdd ? '#10b981' : '#ef4444'};
color: white;
padding: 12px 20px;
border-radius: 25px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 1000;
opacity: 0;
transform: translateX(100px);
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 8px;
`;
document.body.appendChild(toast);
}
toast.innerHTML = `<i class="fas ${isAdd ? 'fa-heart' : 'fa-heart-broken'}"></i> ${message}`;
toast.style.background = isAdd ? '#10b981' : '#ef4444';
// 显示动画
setTimeout(() => {
toast.style.opacity = '1';
toast.style.transform = 'translateX(0)';
}, 10);
// 隐藏动画
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateX(100px)';
setTimeout(() => {
if (toast.parentNode) {
toast.parentNode.removeChild(toast);
}
}, 300);
}, 2000);
}
// 初始化性能监控和移动端优化
logPerformance();
preventDoubleTapZoom();
// 导出函数供全局使用
window.openLightbox = openLightbox;
window.closeLightbox = closeLightbox;
window.prevImage = prevImage;
window.nextImage = nextImage;
window.toggleFavorite = toggleFavorite;

View File

@@ -1,17 +1,78 @@
// 全局变量
let allAlbums = [];
let searchTimeout = 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() {
document.addEventListener('DOMContentLoaded', function () {
// 添加设备类到body
if (isMobile) {
document.body.classList.add('mobile-device');
}
if (isTouchDevice) {
document.body.classList.add('touch-device');
}
loadAlbums();
initSearch();
});
// 初始化搜索功能
function initSearch() {
const searchInput = document.getElementById('search-input');
// 防抖搜索
searchInput.addEventListener('input', function () {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(debouncedSearch, 300);
});
// 移动端优化:搜索框聚焦时自动滚动到可视区域
if (isMobile) {
searchInput.addEventListener('focus', function () {
setTimeout(() => {
searchInput.scrollIntoView({behavior: 'smooth', block: 'center'});
}, 100);
});
}
}
// 防抖搜索
function debouncedSearch() {
searchAlbums();
}
// 显示骨架屏
function showSkeleton(count = 6) {
const container = document.getElementById('albums-container');
container.innerHTML = Array(count).fill(0).map(() => `
<div class="skeleton-card">
<div class="skeleton-cover skeleton"></div>
<div class="skeleton-content">
<div class="skeleton-title skeleton"></div>
<div class="skeleton-meta">
<div class="skeleton-meta-item skeleton"></div>
<div class="skeleton-meta-item skeleton"></div>
</div>
<div class="skeleton-button skeleton"></div>
</div>
</div>
`).join('');
}
// 加载所有相册
async function loadAlbums() {
try {
// 显示骨架屏
showSkeleton();
const response = await fetch(`${API_BASE}/albums`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@@ -19,6 +80,9 @@ async function loadAlbums() {
allAlbums = await response.json();
displayAlbums(allAlbums);
updateStats(allAlbums);
// 初始化图片懒加载
initLazyLoading();
} catch (error) {
console.error('加载相册失败:', error);
showError('加载相册数据失败,请刷新页面重试');
@@ -28,27 +92,33 @@ async function loadAlbums() {
// 搜索相册
async function searchAlbums() {
const searchTerm = document.getElementById('search-input').value.toLowerCase().trim();
if (searchTerm === '') {
// 显示所有相册
displayAlbums(allAlbums);
updateStats(allAlbums);
return;
}
try {
// 显示搜索中的骨架屏
showSkeleton(4);
const response = await fetch(`${API_BASE}/search?q=${encodeURIComponent(searchTerm)}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const filteredAlbums = await response.json();
displayAlbums(filteredAlbums);
if (filteredAlbums.length === 0) {
document.getElementById('stats').innerHTML = `没有找到包含 "${searchTerm}" 的相册`;
} else {
document.getElementById('stats').innerHTML = `找到 ${filteredAlbums.length} 个包含 "${searchTerm}" 的相册`;
}
// 初始化图片懒加载
initLazyLoading();
} catch (error) {
console.error('搜索失败:', error);
showError('搜索失败,请重试');
@@ -58,26 +128,35 @@ async function searchAlbums() {
// 显示相册列表
function displayAlbums(albums) {
const container = document.getElementById('albums-container');
if (albums.length === 0) {
container.innerHTML = '<div class="no-results"><i class="fas fa-search"></i><br>没有找到匹配的相册</div>';
return;
}
container.innerHTML = albums.map(album => {
// 处理封面图片URL
// 处理封面图片URL - 使用懒加载
let coverImageUrl = '/assets/placeholder.svg';
let dataSrc = '';
if (album.cover_image_id) {
coverImageUrl = `/api/thumbnail/${album.cover_image_id}`;
dataSrc = `/api/thumbnail/${album.cover_image_id}`;
coverImageUrl = '/assets/placeholder.svg'; // 初始使用占位图
}
// 格式化日期
const createdDate = new Date(album.created_at).toLocaleDateString('zh-CN');
return `
<div class="album-card">
<div class="album-card" data-album-id="${album.id}">
<div class="album-cover">
<img src="${coverImageUrl}" alt="${album.title}" onerror="this.src='/assets/placeholder.svg'">
<img
src="${coverImageUrl}"
${dataSrc ? `data-src="${dataSrc}"` : ''}
alt="${album.title}"
class="lazy"
onerror="this.src='/assets/placeholder.svg'"
>
</div>
<div class="album-info">
<h3>${album.title}</h3>
@@ -94,6 +173,41 @@ function displayAlbums(albums) {
}).join('');
}
// 初始化图片懒加载
function initLazyLoading() {
if ('IntersectionObserver' in window) {
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy');
delete img.dataset.src;
}
imageObserver.unobserve(img);
}
});
}, {
rootMargin: '50px 0px',
threshold: 0.1
});
document.querySelectorAll('img.lazy').forEach(img => {
imageObserver.observe(img);
});
} else {
// 不支持IntersectionObserver的浏览器回退方案
document.querySelectorAll('img.lazy').forEach(img => {
if (img.dataset.src) {
img.src = img.dataset.src;
img.classList.remove('lazy');
delete img.dataset.src;
}
});
}
}
// 更新统计信息
function updateStats(albums) {
const totalImages = albums.reduce((sum, album) => sum + album.image_count, 0);
@@ -112,4 +226,442 @@ function handleKeyPress(event) {
if (event.key === 'Enter') {
searchAlbums();
}
}
}
// 性能监控
function logPerformance() {
if ('performance' in window) {
window.addEventListener('load', () => {
setTimeout(() => {
const navigationTiming = performance.getEntriesByType('navigation')[0];
console.log('页面加载时间:', navigationTiming.loadEventEnd - navigationTiming.navigationStart, 'ms');
}, 0);
});
}
}
// 移动端优化:防止双击缩放
function preventDoubleTapZoom() {
if (isTouchDevice) {
let lastTouchEnd = 0;
document.addEventListener('touchend', function (event) {
const now = (new Date()).getTime();
if (now - lastTouchEnd <= 300) {
event.preventDefault();
}
lastTouchEnd = now;
}, false);
}
}
// 初始化性能监控和移动端优化
logPerformance();
preventDoubleTapZoom();
// 随机打开相册
function openRandomAlbum() {
if (allAlbums.length === 0) {
alert('暂无相册数据,请稍后再试');
return;
}
const randomIndex = Math.floor(Math.random() * allAlbums.length);
const randomAlbum = allAlbums[randomIndex];
// 添加随机动画效果
const randomButton = document.querySelector('.random-button');
randomButton.style.transform = 'scale(0.95)';
setTimeout(() => {
randomButton.style.transform = '';
}, 200);
// 跳转到随机相册
window.location.href = `/album?id=${randomAlbum.id}`;
}
// 显示收藏夹
function showFavorites() {
// 从后端API获取收藏列表
fetch(`${API_BASE}/favorites`)
.then(response => {
if (!response.ok) {
throw new Error('获取收藏列表失败');
}
return response.json();
})
.then(favoriteImages => {
if (favoriteImages.length === 0) {
alert('收藏夹为空,快去收藏一些喜欢的图片吧!');
return;
}
// 创建收藏夹页面或跳转到收藏夹视图
displayFavorites(favoriteImages);
})
.catch(error => {
console.error('获取收藏列表失败:', error);
alert('获取收藏列表失败,请稍后重试');
});
}
// 显示收藏夹内容
function displayFavorites(favoriteImages) {
const container = document.getElementById('albums-container');
container.innerHTML = `
${favoriteImages.length === 0 ? `
<div class="empty-favorites">
<div class="empty-icon">
<i class="fas fa-heart-broken"></i>
</div>
<h3>收藏夹空空如也</h3>
<p>快去收藏一些喜欢的图片吧!</p>
<button class="explore-button" onclick="loadAlbums()">
<i class="fas fa-compass"></i> 探索相册
</button>
</div>
` : `${favoriteImages.map((fav, index) => `
<div class="favorite-card" onclick="openFavoriteImage('${fav.favorite.album_id}')">
<div class="card-image">
<img src="${API_BASE}/thumbnail/${fav.image.id}"
alt="${fav.image.title || '收藏的图片'}"
loading="lazy">
<div class="card-overlay">
<div class="overlay-content">
<button class="quick-view" onclick="event.stopPropagation(); previewFavorite(${index})">
<i class="fas fa-expand"></i>
</button>
<button class="remove-favorite" onclick="removeFavorite(event, '${fav.favorite.id}')">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
<div class="favorite-badge">
<i class="fas fa-heart"></i>
</div>
</div>
<div class="card-content">
<div class="image-meta">
<span class="meta-item">
<i class="fas fa-calendar"></i>
${formatDate(fav.favorite.created_at)}
</span>
<span class="meta-item">
<i class="fas fa-ruler-combined"></i>
${fav.image.width}×${fav.image.height}
</span>
</div>
</div>
</div>
`).join('')}
`}
`;
// 更新统计信息 - 显示收藏数量
document.getElementById('stats').innerHTML = `<div class="favorites-header">
<div class="header-content">
<div class="header-left">
<div class="favorites-icon">
<i class="fas fa-heart"></i>
</div>
<div class="header-info">
<h1>我的收藏夹</h1>
<p class="favorites-count">共收藏了 <span class="count-number">${favoriteImages.length}</span> 张图片</p>
</div>
</div>
<div class="header-right">
<div class="action-buttons">
<button class="back-button" onclick="loadAlbums()">
<i class="fas fa-arrow-left"></i> 返回首页
</button>
</div>
</div>
</div>
</div>`;
}
// 格式化日期
function formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
}
// 全局变量存储收藏列表和当前预览索引
let currentFavorites = [];
let currentPreviewIndex = -1;
// 预览收藏的图片
function previewFavorite(index) {
// 获取收藏列表
fetch(`${API_BASE}/favorites`)
.then(response => {
if (!response.ok) {
throw new Error('获取收藏列表失败');
}
return response.json();
})
.then(favorites => {
if (favorites && favorites.length > index) {
currentFavorites = favorites;
currentPreviewIndex = index;
showPreviewModal(index);
} else {
alert('图片不存在或已被删除');
}
})
.catch(error => {
console.error('预览图片失败:', error);
alert('预览图片失败,请稍后重试');
});
}
// 显示预览模态框
function showPreviewModal(index) {
const favorite = currentFavorites[index];
// 构建模态框HTML
const modalHtml = `
<div class="preview-modal" id="previewModal">
<div class="preview-overlay" onclick="closePreviewModal()"></div>
<div class="preview-container">
<div class="preview-header">
<div class="preview-title">
<span class="preview-info">来自: ${favorite.album_title}</span>
</div>
<div class="preview-actions">
<button class="preview-nav preview-prev" onclick="navigatePreview(-1)" ${index === 0 ? 'disabled' : ''}>
<i class="fas fa-chevron-left"></i>
</button>
<span class="preview-counter">${index + 1} / ${currentFavorites.length}</span>
<button class="preview-nav preview-next" onclick="navigatePreview(1)" ${index === currentFavorites.length - 1 ? 'disabled' : ''}>
<i class="fas fa-chevron-right"></i>
</button>
<button class="preview-close" onclick="closePreviewModal()">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="preview-content">
<div class="preview-image-container">
<img src="${API_BASE}/original/${favorite.image.id}"
alt="${favorite.image.title || '预览图片'}"
class="preview-image"
id="preview-image"
loading="eager">
</div>
</div>
<div class="preview-footer">
<div class="preview-meta">
<span class="meta-item">
<i class="fas fa-calendar"></i>
${formatDate(favorite.favorite.created_at)}
</span>
<span class="meta-item">
<i class="fas fa-ruler-combined"></i>
${favorite.image.width} × ${favorite.image.height}
</span>
<span class="meta-item">
<i class="fas fa-heart"></i>
已收藏
</span>
</div>
<div class="preview-controls">
<button class="preview-action" onclick="openFavoriteImage('${favorite.favorite.album_id}')">
<i class="fas fa-folder-open"></i> 打开相册
</button>
<button class="preview-action preview-remove" onclick="removeFavoriteFromPreview('${favorite.favorite.id}')">
<i class="fas fa-trash"></i> 取消收藏
</button>
</div>
</div>
</div>
</div>
`;
// 添加到页面
document.body.insertAdjacentHTML('beforeend', modalHtml);
// 显示模态框
setTimeout(() => {
const modal = document.getElementById('previewModal');
modal.classList.add('active');
}, 10);
// 监听键盘事件
document.addEventListener('keydown', handlePreviewKeydown);
}
// 关闭预览模态框
function closePreviewModal() {
const modal = document.getElementById('previewModal');
if (modal) {
modal.classList.remove('active');
setTimeout(() => {
modal.remove();
}, 300);
}
// 移除键盘事件监听
document.removeEventListener('keydown', handlePreviewKeydown);
}
// 导航预览图片
function navigatePreview(direction) {
const newIndex = currentPreviewIndex + direction;
if (newIndex >= 0 && newIndex < currentFavorites.length) {
updatePreviewContent(newIndex);
}
}
// 更新预览内容(不关闭面板)
function updatePreviewContent(newIndex) {
const favorite = currentFavorites[newIndex];
currentPreviewIndex = newIndex;
// 更新标题和相册信息
const titleElement = document.querySelector('.preview-title h3');
const infoElement = document.querySelector('.preview-info');
if (titleElement) titleElement.textContent = favorite.image.title || '未命名图片';
if (infoElement) infoElement.textContent = `来自: ${favorite.album_title}`;
// 更新计数器
const counterElement = document.querySelector('.preview-counter');
if (counterElement) counterElement.textContent = `${newIndex + 1} / ${currentFavorites.length}`;
// 更新导航按钮状态
const prevButton = document.querySelector('.preview-prev');
const nextButton = document.querySelector('.preview-next');
if (prevButton) prevButton.disabled = newIndex === 0;
if (nextButton) nextButton.disabled = newIndex === currentFavorites.length - 1;
// 更新元数据
const metaElements = document.querySelectorAll('.preview-meta .meta-item');
if (metaElements.length >= 3) {
metaElements[0].innerHTML = `<i class="fas fa-calendar"></i> ${formatDate(favorite.favorite.created_at)}`;
metaElements[1].innerHTML = `<i class="fas fa-ruler-combined"></i> ${favorite.image.width} × ${favorite.image.height}`;
}
// 更新操作按钮
const openAlbumButton = document.querySelector('.preview-action:first-child');
const removeButton = document.querySelector('.preview-remove');
if (openAlbumButton) {
openAlbumButton.onclick = () => openFavoriteImage(favorite.favorite.album_id);
}
if (removeButton) {
removeButton.onclick = () => removeFavoriteFromPreview(favorite.favorite.id);
}
// 更新图片
const imageElement = document.getElementById('preview-image');
if (imageElement ) {
// 显示加载状态
imageElement.style.opacity = '0';
// 加载新图片
const newImage = new Image();
newImage.src = `${API_BASE}/original/${favorite.image.id}`;
newImage.alt = favorite.image.title || '预览图片';
newImage.className = 'preview-image';
newImage.onload = function() {
// 替换图片
if (imageElement.parentNode) {
imageElement.parentNode.replaceChild(newImage, imageElement);
// 重新设置ID
newImage.id = 'preview-image';
}
newImage.style.opacity = '1';
};
newImage.onerror = function() {
// 图片加载失败
imageElement.innerHTML = '<i class="fas fa-exclamation-triangle"></i><span>图片加载失败</span>';
};
}
}
// 处理键盘事件
function handlePreviewKeydown(event) {
if (event.key === 'Escape') {
closePreviewModal();
} else if (event.key === 'ArrowLeft') {
navigatePreview(-1);
} else if (event.key === 'ArrowRight') {
navigatePreview(1);
}
}
// 从预览中移除收藏
function removeFavoriteFromPreview(favoriteId) {
if (confirm('确定要从收藏夹移除这张图片吗?')) {
fetch(`${API_BASE}/favorites/${favoriteId}`, {
method: 'DELETE'
})
.then(response => {
if (!response.ok) {
throw new Error('取消收藏失败');
}
return response.json();
})
.then(() => {
closePreviewModal();
// 重新显示收藏夹
showFavorites();
})
.catch(error => {
console.error('取消收藏失败:', error);
alert('取消收藏失败,请稍后重试');
});
}
}
// 排序收藏夹
function sortFavorites(mode) {
// 这里可以实现排序功能
alert('排序功能开发中...');
}
// 从收藏夹移除图片
function removeFavorite(event, favoriteId) {
event.stopPropagation(); // 阻止事件冒泡
if (confirm('确定要从收藏夹移除这张图片吗?')) {
fetch(`${API_BASE}/favorites/${favoriteId}`, {
method: 'DELETE'
})
.then(response => {
if (!response.ok) {
throw new Error('取消收藏失败');
}
return response.json();
})
.then(() => {
// 重新显示收藏夹
showFavorites();
})
.catch(error => {
console.error('取消收藏失败:', error);
alert('取消收藏失败,请稍后重试');
});
}
}
// 打开收藏的图片
function openFavoriteImage(favoriteId) {
// 这里可以跳转到对应的相册页面
// 在实际实现中,我们需要根据favoriteId获取相册信息
window.location.href = `/album?id=${favoriteId}`;
}
// 导出函数供全局使用
window.handleKeyPress = handleKeyPress;
window.searchAlbums = searchAlbums;
window.openRandomAlbum = openRandomAlbum;
window.showFavorites = showFavorites;

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.