ai-image-generator/script.js
skylarGW 88f89e7742
Add files via upload
初始版本:AI图片生成器
2025-08-09 20:27:03 +08:00

293 lines
8.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('imageRequestForm');
const submitBtn = document.querySelector('.submit-btn');
// 表单提交处理
form.addEventListener('submit', function(e) {
e.preventDefault();
handleFormSubmit();
});
// 文件上传预览功能
setupFilePreview();
// 实时表单验证
setupFormValidation();
});
// 处理表单提交
function handleFormSubmit() {
const submitBtn = document.querySelector('.submit-btn');
const originalText = submitBtn.textContent;
// 显示加载状态
submitBtn.innerHTML = '<span class="loading"></span> 正在准备生成...';
submitBtn.disabled = true;
// 收集表单数据
const formData = collectFormData();
// 验证表单数据
if (!validateFormData(formData)) {
resetSubmitButton(submitBtn, originalText);
return;
}
// 保存表单数据到localStorage作为备份
try {
localStorage.setItem('current_form_data', JSON.stringify(formData));
console.log('表单数据已保存到localStorage');
} catch (e) {
console.warn('localStorage不可用将使用URL参数传递数据');
}
// 将表单数据编码为URL参数
const encodedData = encodeURIComponent(JSON.stringify(formData));
// 短暂延迟后跳转到结果页面,携带数据参数
setTimeout(() => {
window.location.href = `results.html?data=${encodedData}`;
}, 1000);
}
// 收集表单数据
function collectFormData() {
const form = document.getElementById('imageRequestForm');
const formData = new FormData(form);
// 转换为对象格式
const data = {
dimensions: {
width: parseInt(formData.get('width')) || 1024,
height: parseInt(formData.get('height')) || 1024,
format: formData.get('format') || 'jpg'
},
style: {
type: formData.get('style') || '',
colorScheme: formData.get('colorScheme') || ''
},
platforms: formData.getAll('platform'),
description: formData.get('description') || '',
targetAudience: formData.get('targetAudience') || '',
files: {
productImages: Array.from(formData.getAll('productImages')).map(file => file.name),
referenceImages: Array.from(formData.getAll('referenceImages')).map(file => file.name),
brandGuide: formData.get('brandGuide') ? formData.get('brandGuide').name : null
}
};
console.log('收集到的表单数据:', data);
return data;
}
// 验证表单数据
function validateFormData(data) {
const errors = [];
// 验证尺寸
if (data.dimensions.width < 100 || data.dimensions.width > 4000) {
errors.push('图片宽度必须在100-4000像素之间');
}
if (data.dimensions.height < 100 || data.dimensions.height > 4000) {
errors.push('图片高度必须在100-4000像素之间');
}
// 验证必填字段
if (!data.description || data.description.trim().length < 10) {
errors.push('请提供至少10个字符的图片描述');
}
if (data.platforms.length === 0) {
errors.push('请至少选择一个应用平台');
}
if (errors.length > 0) {
showError('请修正以下问题:\n' + errors.join('\n'));
return false;
}
return true;
}
// 模拟图片生成API调用
function simulateImageGeneration(data) {
return new Promise((resolve, reject) => {
// 模拟网络延迟
setTimeout(() => {
// 模拟成功率90%
if (Math.random() > 0.1) {
resolve({
success: true,
imageId: 'img_' + Date.now(),
estimatedTime: '2-3分钟'
});
} else {
reject(new Error('服务器暂时繁忙'));
}
}, 2000);
});
}
// 设置文件上传预览
function setupFilePreview() {
const fileInputs = document.querySelectorAll('input[type="file"]');
fileInputs.forEach(input => {
input.addEventListener('change', function(e) {
const files = e.target.files;
showFileInfo(input, files);
});
});
}
// 显示文件信息
function showFileInfo(input, files) {
// 移除之前的文件信息
const existingInfo = input.parentNode.querySelector('.file-info');
if (existingInfo) {
existingInfo.remove();
}
if (files.length > 0) {
const fileInfo = document.createElement('div');
fileInfo.className = 'file-info';
fileInfo.style.marginTop = '10px';
fileInfo.style.padding = '10px';
fileInfo.style.background = '#e6fffa';
fileInfo.style.borderRadius = '6px';
fileInfo.style.fontSize = '0.9rem';
const fileList = Array.from(files).map(file =>
`📎 ${file.name} (${formatFileSize(file.size)})`
).join('<br>');
fileInfo.innerHTML = `<strong>已选择文件:</strong><br>${fileList}`;
input.parentNode.appendChild(fileInfo);
}
}
// 格式化文件大小
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// 设置表单验证
function setupFormValidation() {
const inputs = document.querySelectorAll('input, select, textarea');
inputs.forEach(input => {
input.addEventListener('blur', function() {
validateField(this);
});
});
}
// 验证单个字段
function validateField(field) {
const value = field.value.trim();
let isValid = true;
let message = '';
// 移除之前的错误提示
removeFieldError(field);
// 根据字段类型进行验证
switch(field.name) {
case 'width':
case 'height':
const num = parseInt(value);
if (num < 100 || num > 4000) {
isValid = false;
message = '尺寸必须在100-4000像素之间';
}
break;
case 'description':
if (value.length < 10) {
isValid = false;
message = '描述至少需要10个字符';
}
break;
}
if (!isValid) {
showFieldError(field, message);
}
}
// 显示字段错误
function showFieldError(field, message) {
field.style.borderColor = '#e53e3e';
const errorDiv = document.createElement('div');
errorDiv.className = 'field-error';
errorDiv.style.color = '#e53e3e';
errorDiv.style.fontSize = '0.8rem';
errorDiv.style.marginTop = '5px';
errorDiv.textContent = message;
field.parentNode.appendChild(errorDiv);
}
// 移除字段错误
function removeFieldError(field) {
field.style.borderColor = '#e2e8f0';
const errorDiv = field.parentNode.querySelector('.field-error');
if (errorDiv) {
errorDiv.remove();
}
}
// 重置提交按钮
function resetSubmitButton(btn, originalText) {
btn.innerHTML = originalText;
btn.disabled = false;
}
// 显示成功消息
function showSuccess(message) {
showNotification(message, 'success');
}
// 显示错误消息
function showError(message) {
showNotification(message, 'error');
}
// 显示通知
function showNotification(message, type) {
// 创建通知元素
const notification = document.createElement('div');
notification.style.position = 'fixed';
notification.style.top = '20px';
notification.style.right = '20px';
notification.style.padding = '15px 20px';
notification.style.borderRadius = '8px';
notification.style.color = 'white';
notification.style.fontWeight = '600';
notification.style.zIndex = '1000';
notification.style.maxWidth = '400px';
notification.style.boxShadow = '0 4px 12px rgba(0,0,0,0.3)';
if (type === 'success') {
notification.style.background = '#38a169';
notification.innerHTML = '✅ ' + message;
} else {
notification.style.background = '#e53e3e';
notification.innerHTML = '❌ ' + message;
}
document.body.appendChild(notification);
// 3秒后自动移除
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 3000);
}