// 工具函数集合 // MD5加密函数(使用CryptoJS) function md5(text) { return CryptoJS.MD5(text).toString(); } // 格式化日期时间 function formatDateTime(date) { if (!date) return ''; const d = new Date(date); return d.toLocaleString('zh-CN'); } // 格式化货币 function formatCurrency(amount) { // 处理无效输入 if (amount === undefined || amount === null || amount === '') { return '¥0.00'; } // 转换为数字 const num = parseFloat(amount); // 检查是否为有效数字 if (isNaN(num)) { return '¥0.00'; } return '¥' + num.toFixed(2); } // 验证邮箱格式 function validateEmail(email) { const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return re.test(email); } // 验证手机号格式 function validatePhone(phone) { const re = /^1[3-9]\d{9}$/; return re.test(phone); } // 显示提示消息 function showMessage(message, type = 'info') { // 创建提示元素 const alertDiv = document.createElement('div'); alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`; alertDiv.style.top = '20px'; alertDiv.style.right = '20px'; alertDiv.style.zIndex = '9999'; alertDiv.innerHTML = ` ${message} `; document.body.appendChild(alertDiv); // 3秒后自动移除 setTimeout(() => { if (alertDiv.parentNode) { alertDiv.parentNode.removeChild(alertDiv); } }, 3000); } // 确认对话框 function confirmDialog(message) { return confirm(message); } // 加载动画显示/隐藏 function showLoading() { // 创建加载遮罩 const loadingDiv = document.createElement('div'); loadingDiv.id = 'loading-overlay'; loadingDiv.className = 'position-fixed top-0 start-0 w-100 h-100 d-flex justify-content-center align-items-center'; loadingDiv.style.backgroundColor = 'rgba(0,0,0,0.5)'; loadingDiv.style.zIndex = '9999'; loadingDiv.innerHTML = `
加载中...
`; document.body.appendChild(loadingDiv); } function hideLoading() { const loadingDiv = document.getElementById('loading-overlay'); if (loadingDiv) { loadingDiv.remove(); } } // 表单验证 function validateForm(formId) { const form = document.getElementById(formId); const inputs = form.querySelectorAll('input[required], select[required], textarea[required]'); let isValid = true; inputs.forEach(input => { if (!input.value.trim()) { input.classList.add('is-invalid'); isValid = false; } else { input.classList.remove('is-invalid'); } }); return isValid; } // 数字格式化 function formatNumber(num, decimals = 2) { return parseFloat(num).toFixed(decimals); } // 百分比计算 function calculatePercentage(part, total) { if (total === 0) return 0; return (part / total * 100).toFixed(2); } // 字符串截取 function truncateString(str, length) { if (str.length <= length) return str; return str.substring(0, length) + '...'; } // 生成随机ID function generateId() { return Math.random().toString(36).substr(2, 9); } // 深拷贝对象 function deepClone(obj) { if (obj === null || typeof obj !== 'object') return obj; if (obj instanceof Date) return new Date(obj.getTime()); if (obj instanceof Array) return obj.map(item => deepClone(item)); if (typeof obj === 'object') { const clonedObj = {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { clonedObj[key] = deepClone(obj[key]); } } return clonedObj; } } // 防抖函数 function debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } // 节流函数 function throttle(func, limit) { let inThrottle; return function() { const args = arguments; const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } // 文件大小格式化 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 previewImage(input, previewElementId) { if (input.files && input.files[0]) { const reader = new FileReader(); reader.onload = function(e) { const preview = document.getElementById(previewElementId); if (preview) { preview.innerHTML = ``; } }; reader.readAsDataURL(input.files[0]); } } // 检查浏览器支持 function checkBrowserSupport() { const features = { localStorage: typeof(Storage) !== "undefined", fileUpload: !!window.File && !!window.FileReader && !!window.FileList && !!window.Blob, dragAndDrop: 'draggable' in document.createElement('span'), canvas: !!document.createElement('canvas').getContext, webGL: (function() { try { const canvas = document.createElement('canvas'); return !!(window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))); } catch(e) { return false; } })() }; return features; } // 导出为全局函数 window.Utils = { md5, formatDateTime, formatCurrency, validateEmail, validatePhone, showMessage, confirmDialog, showLoading, hideLoading, validateForm, formatNumber, calculatePercentage, truncateString, generateId, deepClone, debounce, throttle, formatFileSize, previewImage, checkBrowserSupport };