// 通用功能:暗黑模式切换和页面初始化
document.addEventListener('DOMContentLoaded', function() {
// 初始化统计数据
initStatistics();
// 检查是否存在暗黑模式偏好
const darkMode = localStorage.getItem('darkMode') === 'true';
if (darkMode) {
document.body.classList.add('dark-mode');
document.querySelectorAll('.dark-mode-toggle i, #dark-mode-toggle i, #dark-mode-toggle-sidebar i').forEach(icon => {
icon.classList.remove('fa-moon');
icon.classList.add('fa-sun');
});
// 使用ID选择器更新主题状态文字
const themeStatus = document.getElementById('theme-status');
if (themeStatus) {
themeStatus.textContent = '当前: 深色';
}
}
// 添加侧边栏链接的点击处理
const sidebarLinks = document.querySelectorAll('#sidebar a[href="#settings"], #sidebar a[href="#about"], #sidebar a[href="#feedback"]');
sidebarLinks.forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const linkType = this.getAttribute('href').substring(1); // 移除#符号
if (linkType === 'settings') {
openSettingsPanel();
} else if (linkType === 'about') {
openAboutPanel();
} else if (linkType === 'feedback') {
showFeedbackDialog();
}
});
});
// 显示反馈对话框
function showFeedbackDialog() {
// 检查是否已存在对话框
let dialog = document.getElementById('feedback-dialog');
if (dialog) {
document.body.removeChild(dialog);
}
// 创建对话框
dialog = document.createElement('div');
dialog.id = 'feedback-dialog';
dialog.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50';
dialog.innerHTML = `
`;
// 添加到页面
document.body.appendChild(dialog);
// 添加关闭事件
dialog.querySelectorAll('.dialog-close').forEach(btn => {
btn.addEventListener('click', function() {
document.body.removeChild(dialog);
});
});
// 提交反馈
dialog.querySelector('#submit-feedback').addEventListener('click', function() {
// 这里可以添加实际的提交逻辑
document.body.removeChild(dialog);
// 显示成功消息
const messageDiv = document.createElement('div');
messageDiv.className = 'fixed bottom-4 right-4 p-4 rounded-md shadow-lg z-50 bg-green-500 text-white';
messageDiv.innerHTML = '感谢您的反馈!我们将尽快处理。';
document.body.appendChild(messageDiv);
// 3秒后移除
setTimeout(() => {
messageDiv.style.opacity = '0';
messageDiv.style.transition = 'opacity 0.3s';
setTimeout(() => {
document.body.removeChild(messageDiv);
}, 300);
}, 3000);
});
// 点击背景关闭
dialog.addEventListener('click', function(e) {
if (e.target === dialog) {
document.body.removeChild(dialog);
}
});
}
function openSettingsPanel() {
const settingsPanel = document.getElementById('settings-panel');
if (settingsPanel) {
settingsPanel.classList.remove('hidden');
}
}
function openAboutPanel() {
const aboutPanel = document.getElementById('about-panel');
if (aboutPanel) {
aboutPanel.classList.remove('hidden');
}
}
// 暗黑模式切换按钮
const darkModeToggles = document.querySelectorAll('#dark-mode-toggle, #dark-mode-toggle-sidebar');
if (darkModeToggles.length) {
darkModeToggles.forEach(toggle => {
toggle.addEventListener('click', function() {
console.log('暗黑模式切换按钮被点击');
document.body.classList.toggle('dark-mode');
const isDarkMode = document.body.classList.contains('dark-mode');
localStorage.setItem('darkMode', isDarkMode);
// 更改所有图标
const icons = document.querySelectorAll('#dark-mode-toggle i, #dark-mode-toggle-sidebar i');
icons.forEach(icon => {
if (isDarkMode) {
icon.classList.remove('fa-moon');
icon.classList.add('fa-sun');
} else {
icon.classList.remove('fa-sun');
icon.classList.add('fa-moon');
}
});
// 更新侧边栏模式文本
const themeStatus = document.getElementById('theme-status');
if (themeStatus) {
themeStatus.textContent = isDarkMode ? '当前: 深色' : '当前: 浅色';
console.log('更新暗黑模式文字为:', themeStatus.textContent);
} else {
console.log('未找到暗黑模式文字元素');
}
});
});
}
// 菜单收藏按钮交互
const favoriteButtons = document.querySelectorAll('.far.fa-heart');
favoriteButtons.forEach(btn => {
btn.addEventListener('click', function() {
this.classList.toggle('far');
this.classList.toggle('fas');
this.classList.toggle('text-red-500');
// 显示收藏提示(实际项目可添加toast提示)
console.log('收藏状态已更改');
});
});
// 添加卡片悬浮效果
const cards = document.querySelectorAll('.bg-white.rounded-lg');
cards.forEach(card => {
card.classList.add('transition-all', 'duration-300', 'hover-card-shadow');
});
// 工具卡片点击跟踪
const toolCards = document.querySelectorAll('.group.bg-white');
toolCards.forEach(card => {
card.addEventListener('click', function(e) {
if (!e.target.closest('a') && !e.target.closest('button')) {
const link = this.querySelector('a');
if (link && !link.hasAttribute('disabled')) {
link.click();
}
}
});
});
// 初始化工具提示 (Tooltip)
initTooltips();
// 为评分星星添加互动效果
const starContainers = document.querySelectorAll('.flex.items-center .flex:has(.fa-star)');
starContainers.forEach(container => {
const stars = container.querySelectorAll('i');
stars.forEach((star, index) => {
star.addEventListener('mouseover', () => {
for (let i = 0; i <= index; i++) {
stars[i].classList.add('text-yellow-500');
}
});
star.addEventListener('mouseout', () => {
stars.forEach(s => {
if (!s.classList.contains('text-yellow-400')) {
s.classList.remove('text-yellow-500');
}
});
});
});
});
// 检测当前页面并加载相应功能
const currentPath = window.location.pathname;
if (currentPath.includes('video.html')) {
initVideoParser();
} else if (currentPath.includes('image.html')) {
initImageConverter();
} else {
// 主页特定功能
initMainPageFeatures();
}
});
// 工具提示初始化
function initTooltips() {
const tooltipTriggers = document.querySelectorAll('[data-tooltip]');
tooltipTriggers.forEach(trigger => {
trigger.addEventListener('mouseenter', function() {
const tooltipText = this.getAttribute('data-tooltip');
const tooltip = document.createElement('div');
tooltip.className = 'absolute z-50 px-2 py-1 text-xs text-white bg-gray-800 rounded shadow-lg transition-opacity duration-300';
tooltip.textContent = tooltipText;
tooltip.style.opacity = '0';
tooltip.style.bottom = 'calc(100% + 5px)';
tooltip.style.left = '50%';
tooltip.style.transform = 'translateX(-50%)';
this.style.position = 'relative';
this.appendChild(tooltip);
setTimeout(() => {
tooltip.style.opacity = '1';
}, 10);
});
trigger.addEventListener('mouseleave', function() {
const tooltip = this.querySelector('div');
if (tooltip) {
tooltip.style.opacity = '0';
setTimeout(() => {
tooltip.remove();
}, 300);
}
});
});
}
// 主页特定功能
function initMainPageFeatures() {
// 添加滚动到顶部按钮
const scrollTopBtn = document.createElement('button');
scrollTopBtn.className = 'fab-button hidden';
scrollTopBtn.innerHTML = '';
scrollTopBtn.setAttribute('data-tooltip', '回到顶部');
document.body.appendChild(scrollTopBtn);
// 监听滚动显示/隐藏回到顶部按钮
window.addEventListener('scroll', function() {
if (window.pageYOffset > 300) {
scrollTopBtn.classList.remove('hidden');
} else {
scrollTopBtn.classList.add('hidden');
}
});
// 回到顶部功能
scrollTopBtn.addEventListener('click', function() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
// 平滑滚动到锚点
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href');
if (targetId !== '#') {
const targetElement = document.querySelector(targetId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth'
});
}
}
});
});
// 导航项目激活状态
const navItems = document.querySelectorAll('#sidebar a[href^="#"]');
const sections = document.querySelectorAll('main > div[id]');
window.addEventListener('scroll', function() {
let current = '';
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= sectionTop - 200) {
current = section.getAttribute('id');
}
});
navItems.forEach(navItem => {
navItem.classList.remove('active-nav-item');
const href = navItem.getAttribute('href').substring(1);
if (href === current) {
navItem.classList.add('active-nav-item');
}
});
});
// 工具搜索功能
const searchInputs = document.querySelectorAll('input[placeholder="搜索工具..."]');
searchInputs.forEach(input => {
input.addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
const searchTerm = this.value.toLowerCase().trim();
if (searchTerm) {
// 搜索逻辑,这里只是简单模拟
const toolCards = document.querySelectorAll('.group.bg-white');
let found = false;
toolCards.forEach(card => {
const title = card.querySelector('h3').textContent.toLowerCase();
const desc = card.querySelector('p.text-gray-600, p.text-gray-500').textContent.toLowerCase();
if (title.includes(searchTerm) || desc.includes(searchTerm)) {
card.style.border = '2px solid #60a5fa';
setTimeout(() => {
card.style.border = '';
}, 3000);
card.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
found = true;
return false; // 跳出forEach
}
});
if (!found) {
alert('未找到相关工具,请尝试其他关键词');
}
}
}
});
});
// 初始化订阅表单
const subscribeForm = document.querySelector('footer input[type="email"]').closest('div');
if (subscribeForm) {
const subscribeBtn = subscribeForm.querySelector('button');
const emailInput = subscribeForm.querySelector('input[type="email"]');
subscribeBtn.addEventListener('click', function() {
const email = emailInput.value.trim();
if (email && validateEmail(email)) {
// 模拟订阅成功
const originalText = this.textContent;
this.innerHTML = '成功';
emailInput.value = '';
setTimeout(() => {
this.textContent = originalText;
}, 2000);
} else {
emailInput.classList.add('border-red-500');
setTimeout(() => {
emailInput.classList.remove('border-red-500');
}, 1500);
}
});
}
}
// 邮箱验证函数
function validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
// VIP视频解析功能
function initVideoParser() {
const videoUrl = document.getElementById('video-url');
const parseButton = document.getElementById('parse-button');
const videoIframe = document.getElementById('video-iframe');
const videoPlaceholder = document.getElementById('video-placeholder');
if (videoUrl && parseButton) {
// 输入框动画效果
videoUrl.addEventListener('focus', function() {
this.parentElement.classList.add('ring-2', 'ring-gray-500', 'ring-opacity-50');
});
videoUrl.addEventListener('blur', function() {
this.parentElement.classList.remove('ring-2', 'ring-gray-500', 'ring-opacity-50');
});
// 快捷网站点击填充
const siteLinks = document.querySelectorAll('.flex.flex-wrap.gap-2 a');
siteLinks.forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const url = this.getAttribute('href');
videoUrl.value = url;
videoUrl.focus();
});
});
// 解析按钮点击
parseButton.addEventListener('click', function() {
const url = videoUrl.value.trim();
if (url) {
// 这里假设您已经实现了解析功能的后端API
// 这里只是模拟UI交互
// 显示加载状态
parseButton.innerHTML = '解析中...';
parseButton.disabled = true;
// 添加历史记录到本地存储
addToHistory(url);
// 模拟解析过程
setTimeout(function() {
// 假设成功解析
videoPlaceholder.classList.add('hidden');
videoIframe.classList.remove('hidden');
// 此处应设置为实际的解析后的视频地址
// 这里只是模拟UI展示,实际使用时请替换为真实接口
videoIframe.src = `https://your-actual-video-parser-api.com/parse?url=${encodeURIComponent(url)}`;
// 恢复按钮状态
parseButton.innerHTML = '立即解析';
parseButton.disabled = false;
// 记录使用次数
incrementUsageCount();
}, 1500);
} else {
// 提示用户输入URL
showInputError(videoUrl);
}
});
// 监听Enter键提交
videoUrl.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
parseButton.click();
}
});
}
// 添加返回顶部按钮
addBackToTopButton();
}
// 图片格式转换功能
function initImageConverter() {
const fileInput = document.getElementById('file-input');
const uploadButton = document.getElementById('upload-button');
const uploadContainer = document.getElementById('upload-container');
const uploadPrompt = document.getElementById('upload-prompt');
const uploadPreview = document.getElementById('upload-preview');
const previewImage = document.getElementById('preview-image');
const fileInfo = document.getElementById('file-info');
const changeFileBtn = document.getElementById('change-file');
const convertButton = document.getElementById('convert-button');
const formatSelect = document.getElementById('format-select');
const qualitySlider = document.getElementById('quality-slider');
const qualityValue = document.getElementById('quality-value');
const resizeToggle = document.getElementById('resize-toggle');
const resizeOptions = document.getElementById('resize-options');
const resultSection = document.getElementById('result-section');
const resultImage = document.getElementById('result-image');
const resultInfo = document.getElementById('result-info');
const downloadLink = document.getElementById('download-link');
let selectedFile = null;
// 增强上传按钮动画
if (uploadButton) {
uploadButton.addEventListener('mouseenter', function() {
this.classList.add('shadow-md', 'scale-105');
});
uploadButton.addEventListener('mouseleave', function() {
this.classList.remove('shadow-md', 'scale-105');
});
uploadButton.addEventListener('click', function() {
fileInput.click();
});
}
// 增强上传区域交互
if (uploadContainer) {
// 添加脉冲动画效果
uploadContainer.classList.add('relative');
const pulseIndicator = document.createElement('div');
pulseIndicator.className = 'absolute inset-0 border-2 border-gray-400 rounded-lg pulse opacity-0';
uploadContainer.prepend(pulseIndicator);
uploadContainer.addEventListener('click', function(e) {
if (!e.target.closest('button')) {
pulseIndicator.classList.remove('opacity-0');
setTimeout(() => {
pulseIndicator.classList.add('opacity-0');
}, 800);
fileInput.click();
}
});
// 拖放功能强化
uploadContainer.addEventListener('dragover', function(e) {
e.preventDefault();
this.classList.add('drag-over');
});
uploadContainer.addEventListener('dragleave', function() {
this.classList.remove('drag-over');
});
uploadContainer.addEventListener('drop', function(e) {
e.preventDefault();
this.classList.remove('drag-over');
if (e.dataTransfer.files.length) {
handleFileSelect(e.dataTransfer.files[0]);
}
});
}
// 文件选择增强
if (fileInput) {
fileInput.addEventListener('change', function() {
if (this.files.length) {
handleFileSelect(this.files[0]);
}
});
}
// 更换图片按钮增强
if (changeFileBtn) {
changeFileBtn.addEventListener('mouseenter', function() {
this.innerHTML = '更换图片';
});
changeFileBtn.addEventListener('mouseleave', function() {
this.textContent = '更换图片';
});
changeFileBtn.addEventListener('click', function() {
resetUploadUI();
});
}
// 切换尺寸调整选项增强
if (resizeToggle) {
resizeToggle.addEventListener('change', function() {
if (this.checked) {
resizeOptions.classList.remove('hidden');
resizeOptions.classList.add('fade-in');
} else {
resizeOptions.classList.add('hidden');
resizeOptions.classList.remove('fade-in');
}
});
}
// 质量滑块增强
if (qualitySlider) {
qualitySlider.addEventListener('input', function() {
qualityValue.textContent = this.value;
// 视觉反馈
if (this.value < 40) {
qualityValue.className = 'text-red-500';
} else if (this.value < 70) {
qualityValue.className = 'text-yellow-500';
} else {
qualityValue.className = 'text-green-500';
}
});
// 触发一次更新颜色
qualitySlider.dispatchEvent(new Event('input'));
}
// 转换按钮增强
if (convertButton) {
convertButton.addEventListener('mouseenter', function() {
if (!this.disabled) {
this.classList.add('shadow-md');
}
});
convertButton.addEventListener('mouseleave', function() {
this.classList.remove('shadow-md');
});
convertButton.addEventListener('click', function() {
if (!selectedFile) return;
// 显示加载状态
convertButton.innerHTML = '处理中...';
convertButton.disabled = true;
// 获取转换参数
const format = formatSelect.value;
const quality = qualitySlider.value;
const resize = resizeToggle.checked;
const width = document.getElementById('width-input').value;
const height = document.getElementById('height-input').value;
// 添加历史记录
addToHistory(`图片转换: ${selectedFile.name} → ${format.toUpperCase()}`);
// 这里应是实际的图片处理逻辑
// 这里只做UI展示模拟
setTimeout(function() {
// 模拟转换结果
resultSection.classList.remove('hidden');
resultSection.classList.add('fade-in');
resultSection.scrollIntoView({ behavior: 'smooth' });
// 在实际应用中,这里应设置为转换后的图片
resultImage.src = previewImage.src;
// 显示文件信息
const fileName = selectedFile.name.split('.')[0];
resultInfo.textContent = `${fileName}.${format} - ${Math.round(selectedFile.size / 1024)}KB`;
// 设置下载链接(实际应用中应提供转换后的图片下载)
downloadLink.href = previewImage.src;
downloadLink.download = `${fileName}.${format}`;
// 恢复按钮状态
convertButton.innerHTML = '开始转换';
convertButton.disabled = false;
// 记录使用次数
incrementUsageCount();
}, 1500);
});
}
// 格式选择增强
if (formatSelect) {
formatSelect.addEventListener('change', function() {
// 视觉反馈
const formatOptions = {
'jpg': { icon: 'fa-file-image', color: 'text-blue-500' },
'png': { icon: 'fa-file-image', color: 'text-green-500' },
'webp': { icon: 'fa-file-image', color: 'text-purple-500' },
'gif': { icon: 'fa-film', color: 'text-yellow-500' },
'bmp': { icon: 'fa-file-image', color: 'text-gray-500' }
};
const format = this.value;
const option = formatOptions[format] || formatOptions['jpg'];
// 更新标签视觉反馈
const label = this.previousElementSibling;
if (label) {
label.innerHTML = `目标格式 `;
}
});
// 触发一次更新
formatSelect.dispatchEvent(new Event('change'));
}
// 处理文件选择
function handleFileSelect(file) {
if (!file.type.startsWith('image/')) {
alert('请选择图片文件');
return;
}
selectedFile = file;
// 显示预览
uploadPrompt.classList.add('hidden');
uploadPreview.classList.remove('hidden');
uploadPreview.classList.add('fade-in');
// 读取文件预览
const reader = new FileReader();
reader.onload = function(e) {
previewImage.src = e.target.result;
// 获取图片尺寸用于显示
const img = new Image();
img.onload = function() {
fileInfo.innerHTML = `${file.name} - ${Math.round(file.size / 1024)}KB
${this.width} × ${this.height} 像素`;
// 自动填充调整尺寸字段
document.getElementById('width-input').value = this.width;
document.getElementById('height-input').value = this.height;
};
img.src = e.target.result;
convertButton.disabled = false;
// 隐藏可能显示的结果区域
resultSection.classList.add('hidden');
};
reader.readAsDataURL(file);
}
// 重置上传UI
function resetUploadUI() {
selectedFile = null;
fileInput.value = '';
uploadPrompt.classList.remove('hidden');
uploadPreview.classList.add('hidden');
uploadPreview.classList.remove('fade-in');
convertButton.disabled = true;
}
// 添加返回顶部按钮
addBackToTopButton();
}
// 工具使用历史记录
function addToHistory(item) {
let history = JSON.parse(localStorage.getItem('toolHistory') || '[]');
history.unshift({
item: item,
timestamp: new Date().toISOString()
});
// 限制历史记录数量
if (history.length > 10) {
history = history.slice(0, 10);
}
localStorage.setItem('toolHistory', JSON.stringify(history));
}
// 使用次数统计
function incrementUsageCount() {
incrementStatValue('usageCount');
}
// 显示输入错误
function showInputError(inputElement) {
inputElement.classList.add('border-red-500');
inputElement.classList.add('shake');
setTimeout(() => {
inputElement.classList.remove('border-red-500');
inputElement.classList.remove('shake');
}, 1000);
}
// 添加返回顶部按钮
function addBackToTopButton() {
const scrollTopBtn = document.createElement('button');
scrollTopBtn.className = 'fab-button hidden';
scrollTopBtn.innerHTML = '';
document.body.appendChild(scrollTopBtn);
window.addEventListener('scroll', function() {
if (window.pageYOffset > 300) {
scrollTopBtn.classList.remove('hidden');
} else {
scrollTopBtn.classList.add('hidden');
}
});
scrollTopBtn.addEventListener('click', function() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
}
// 统计数据初始化和动态更新
function initStatistics() {
// 从localStorage获取上次访问时间
const lastVisit = localStorage.getItem('lastVisit');
const now = new Date().getTime();
// 如果是首次访问或者距离上次访问超过6小时,增加访问人数
if (!lastVisit || (now - parseInt(lastVisit)) > 6 * 60 * 60 * 1000) {
incrementStatValue('visitorCount');
localStorage.setItem('lastVisit', now.toString());
}
// 获取并显示统计数据
updateStatisticsDisplay();
// 设置定时器,每10秒随机更新一次统计数据以模拟实时变化
setInterval(updateStatisticsDisplay, 10000);
}
// 更新统计数据显示
function updateStatisticsDisplay() {
// 使用更精确的选择器来找到各个统计卡片
const statCards = document.querySelectorAll('.bg-white.rounded-lg');
statCards.forEach(card => {
const title = card.querySelector('h3.text-gray-500.text-sm');
if (!title) return;
const countElem = card.querySelector('.text-2xl.font-bold');
if (!countElem) return;
if (title.textContent.includes('访问人数')) {
updateVisitorCount(countElem);
} else if (title.textContent.includes('使用次数')) {
updateUsageCount(countElem);
}
});
}
// 更新访问人数显示
function updateVisitorCount(element) {
// 获取当前计数或使用默认值
let count = getStatValue('visitorCount') || 1254;
// 添加随机变动以模拟实时数据
const change = Math.random() > 0.7 ? 1 : 0; // 30%的几率增加1
if (change) {
count += 1;
saveStatValue('visitorCount', count);
}
// 更新显示
if (element) {
element.textContent = count.toLocaleString();
}
}
// 更新使用次数显示
function updateUsageCount(element) {
// 获取当前计数或使用默认值
let count = getStatValue('usageCount') || 5840;
// 添加随机变动以模拟实时数据
const change = Math.random() > 0.5 ? Math.floor(Math.random() * 3) + 1 : 0; // 50%的几率增加1-3
if (change) {
count += change;
saveStatValue('usageCount', count);
}
// 更新显示
if (element) {
element.textContent = count.toLocaleString();
}
}
// 增加指定统计值
function incrementStatValue(key, amount = 1) {
const currentValue = getStatValue(key) || 0;
saveStatValue(key, currentValue + amount);
return currentValue + amount;
}
// 获取统计值
function getStatValue(key) {
const value = localStorage.getItem(key);
return value ? parseInt(value) : null;
}
// 保存统计值
function saveStatValue(key, value) {
localStorage.setItem(key, value.toString());
}