/** * 无障碍访问工具类 * 提供屏幕阅读器支持、键盘导航、高对比度模式等功能 */ class AccessibilityUtils { constructor() { this.isHighContrast = false; this.isLargeText = false; this.isScreenReaderMode = false; this.focusVisible = true; this.currentFocusIndex = 0; this.focusableElements = []; this.init(); } /** * 初始化无障碍功能 */ init() { this.setupKeyboardNavigation(); this.setupFocusManagement(); this.setupScreenReaderSupport(); this.loadAccessibilitySettings(); } /** * 设置键盘导航 */ setupKeyboardNavigation() { document.addEventListener('keydown', (e) => { switch (e.key) { case 'Tab': this.handleTabNavigation(e); break; case 'Enter': case ' ': this.handleActivation(e); break; case 'Escape': this.handleEscape(e); break; case 'ArrowUp': case 'ArrowDown': case 'ArrowLeft': case 'ArrowRight': this.handleArrowNavigation(e); break; } }); // 检测键盘使用,显示焦点指示器 document.addEventListener('keydown', () => { this.focusVisible = true; document.body.classList.add('keyboard-navigation'); }); // 检测鼠标使用,隐藏焦点指示器 document.addEventListener('mousedown', () => { this.focusVisible = false; document.body.classList.remove('keyboard-navigation'); }); } /** * 处理Tab导航 * @param {KeyboardEvent} e - 键盘事件 */ handleTabNavigation(e) { this.updateFocusableElements(); if (this.focusableElements.length === 0) return; if (e.shiftKey) { // Shift + Tab - 反向导航 this.currentFocusIndex = this.currentFocusIndex <= 0 ? this.focusableElements.length - 1 : this.currentFocusIndex - 1; } else { // Tab - 正向导航 this.currentFocusIndex = this.currentFocusIndex >= this.focusableElements.length - 1 ? 0 : this.currentFocusIndex + 1; } this.focusableElements[this.currentFocusIndex]?.focus(); e.preventDefault(); } /** * 处理激活操作 * @param {KeyboardEvent} e - 键盘事件 */ handleActivation(e) { const activeElement = document.activeElement; if (activeElement && activeElement.click) { activeElement.click(); e.preventDefault(); } } /** * 处理Escape键 * @param {KeyboardEvent} e - 键盘事件 */ handleEscape(e) { // 关闭模态框、菜单等 const modal = document.querySelector('.modal:not([style*="display: none"])'); const menu = document.querySelector('.dropdown-menu.show, .longpress-menu'); if (modal) { this.closeModal(modal); } else if (menu) { menu.remove(); } } /** * 处理方向键导航 * @param {KeyboardEvent} e - 键盘事件 */ handleArrowNavigation(e) { const currentElement = document.activeElement; const container = currentElement.closest('.grid-layout, .menu-section, .stats-section'); if (!container) return; const focusableInContainer = this.getFocusableElements(container); const currentIndex = focusableInContainer.indexOf(currentElement); if (currentIndex === -1) return; let nextIndex = currentIndex; const containerRect = container.getBoundingClientRect(); const currentRect = currentElement.getBoundingClientRect(); switch (e.key) { case 'ArrowUp': nextIndex = this.findElementAbove(focusableInContainer, currentIndex, currentRect); break; case 'ArrowDown': nextIndex = this.findElementBelow(focusableInContainer, currentIndex, currentRect); break; case 'ArrowLeft': nextIndex = Math.max(0, currentIndex - 1); break; case 'ArrowRight': nextIndex = Math.min(focusableInContainer.length - 1, currentIndex + 1); break; } if (nextIndex !== currentIndex) { focusableInContainer[nextIndex]?.focus(); e.preventDefault(); } } /** * 查找上方元素 */ findElementAbove(elements, currentIndex, currentRect) { let bestIndex = currentIndex; let minDistance = Infinity; for (let i = 0; i < elements.length; i++) { if (i === currentIndex) continue; const rect = elements[i].getBoundingClientRect(); if (rect.bottom <= currentRect.top) { const distance = Math.abs(rect.left - currentRect.left) + (currentRect.top - rect.bottom); if (distance < minDistance) { minDistance = distance; bestIndex = i; } } } return bestIndex; } /** * 查找下方元素 */ findElementBelow(elements, currentIndex, currentRect) { let bestIndex = currentIndex; let minDistance = Infinity; for (let i = 0; i < elements.length; i++) { if (i === currentIndex) continue; const rect = elements[i].getBoundingClientRect(); if (rect.top >= currentRect.bottom) { const distance = Math.abs(rect.left - currentRect.left) + (rect.top - currentRect.bottom); if (distance < minDistance) { minDistance = distance; bestIndex = i; } } } return bestIndex; } /** * 设置焦点管理 */ setupFocusManagement() { // 焦点指示器样式 const focusStyles = ` .keyboard-navigation *:focus { outline: 2px solid rgb(93, 135, 255) !important; outline-offset: 2px !important; } .keyboard-navigation .touchable:focus { outline: 2px solid rgb(93, 135, 255) !important; outline-offset: 2px !important; box-shadow: 0 0 0 4px rgba(93, 135, 255, 0.2) !important; } `; const styleSheet = document.createElement('style'); styleSheet.textContent = focusStyles; document.head.appendChild(styleSheet); // 焦点陷阱(用于模态框) this.setupFocusTrap(); } /** * 设置焦点陷阱 */ setupFocusTrap() { document.addEventListener('focusin', (e) => { const modal = document.querySelector('.modal:not([style*="display: none"])'); if (modal && !modal.contains(e.target)) { const firstFocusable = this.getFocusableElements(modal)[0]; firstFocusable?.focus(); } }); } /** * 更新可聚焦元素列表 */ updateFocusableElements() { this.focusableElements = this.getFocusableElements(document); } /** * 获取可聚焦元素 * @param {Element} container - 容器元素 * @returns {Element[]} 可聚焦元素数组 */ getFocusableElements(container = document) { const focusableSelectors = [ 'button:not([disabled])', '[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', '[tabindex]:not([tabindex="-1"])', '.touchable', '.service-item', '.menu-item', '.stat-card', ].join(', '); return Array.from(container.querySelectorAll(focusableSelectors)).filter((el) => { return ( el.offsetParent !== null && !el.hasAttribute('disabled') && !el.classList.contains('sr-only') ); }); } /** * 设置屏幕阅读器支持 */ setupScreenReaderSupport() { // 动态添加ARIA标签 this.addAriaLabels(); // 实时区域更新 this.setupLiveRegions(); // 页面标题更新 this.setupPageTitleUpdates(); } /** * 添加ARIA标签 */ addAriaLabels() { // 为服务项添加描述 document.querySelectorAll('.service-item').forEach((item) => { const title = item.querySelector('.service-title')?.textContent; if (title && !item.hasAttribute('aria-label')) { item.setAttribute('aria-label', `${title}服务`); item.setAttribute('role', 'button'); item.setAttribute('tabindex', '0'); } }); // 为统计卡片添加描述 document.querySelectorAll('.stat-card').forEach((card) => { const number = card.querySelector('.stat-number')?.textContent; const label = card.querySelector('.stat-label')?.textContent; if (number && label && !card.hasAttribute('aria-label')) { card.setAttribute('aria-label', `${label}:${number}`); card.setAttribute('role', 'button'); card.setAttribute('tabindex', '0'); } }); // 为导航按钮添加描述 document.querySelectorAll('.nav-tab').forEach((tab) => { const label = tab.querySelector('.nav-label')?.textContent; if (label && !tab.hasAttribute('aria-label')) { tab.setAttribute('aria-label', `导航到${label}页面`); } }); } /** * 设置实时区域 */ setupLiveRegions() { // 创建实时区域用于通知 const liveRegion = document.createElement('div'); liveRegion.setAttribute('aria-live', 'polite'); liveRegion.setAttribute('aria-atomic', 'true'); liveRegion.className = 'sr-only'; liveRegion.id = 'live-region'; document.body.appendChild(liveRegion); // 监听toast消息 const originalShowToast = uni.showToast; uni.showToast = (options) => { this.announceToScreenReader(options.title || options.content); return originalShowToast(options); }; } /** * 向屏幕阅读器宣布消息 * @param {string} message - 消息内容 */ announceToScreenReader(message) { const liveRegion = document.getElementById('live-region'); if (liveRegion) { liveRegion.textContent = message; // 清空内容以便下次宣布 setTimeout(() => { liveRegion.textContent = ''; }, 1000); } } /** * 设置页面标题更新 */ setupPageTitleUpdates() { // 监听路由变化,更新页面标题 const originalSwitchTab = uni.switchTab; uni.switchTab = (options) => { const pageTitles = { '/pages/index/index': '智慧校园 - 首页', '/pages/workbench/index': '智慧校园 - 办公中心', '/pages/profile/index': '智慧校园 - 我的', }; const title = pageTitles[options.url]; if (title) { document.title = title; this.announceToScreenReader(`已切换到${title.split(' - ')[1]}页面`); } return originalSwitchTab(options); }; } /** * 启用高对比度模式 */ enableHighContrast() { this.isHighContrast = true; document.body.classList.add('high-contrast'); this.saveAccessibilitySettings(); this.announceToScreenReader('已启用高对比度模式'); } /** * 禁用高对比度模式 */ disableHighContrast() { this.isHighContrast = false; document.body.classList.remove('high-contrast'); this.saveAccessibilitySettings(); this.announceToScreenReader('已禁用高对比度模式'); } /** * 启用大字体模式 */ enableLargeText() { this.isLargeText = true; document.body.classList.add('large-text'); this.saveAccessibilitySettings(); this.announceToScreenReader('已启用大字体模式'); } /** * 禁用大字体模式 */ disableLargeText() { this.isLargeText = false; document.body.classList.remove('large-text'); this.saveAccessibilitySettings(); this.announceToScreenReader('已禁用大字体模式'); } /** * 启用屏幕阅读器模式 */ enableScreenReaderMode() { this.isScreenReaderMode = true; document.body.classList.add('screen-reader-mode'); // 隐藏装饰性动画 const style = document.createElement('style'); style.id = 'screen-reader-styles'; style.textContent = ` .screen-reader-mode * { animation: none !important; transition: none !important; } .screen-reader-mode .decorative { display: none !important; } `; document.head.appendChild(style); this.saveAccessibilitySettings(); this.announceToScreenReader('已启用屏幕阅读器优化模式'); } /** * 禁用屏幕阅读器模式 */ disableScreenReaderMode() { this.isScreenReaderMode = false; document.body.classList.remove('screen-reader-mode'); const style = document.getElementById('screen-reader-styles'); if (style) style.remove(); this.saveAccessibilitySettings(); this.announceToScreenReader('已禁用屏幕阅读器优化模式'); } /** * 保存无障碍设置 */ saveAccessibilitySettings() { const settings = { highContrast: this.isHighContrast, largeText: this.isLargeText, screenReaderMode: this.isScreenReaderMode, }; uni.setStorageSync('accessibility-settings', settings); } /** * 加载无障碍设置 */ loadAccessibilitySettings() { try { const settings = uni.getStorageSync('accessibility-settings'); if (settings) { if (settings.highContrast) this.enableHighContrast(); if (settings.largeText) this.enableLargeText(); if (settings.screenReaderMode) this.enableScreenReaderMode(); } } catch (e) { console.warn('Failed to load accessibility settings:', e); } } /** * 添加语义化结构 */ addSemanticStructure() { // 添加主要地标 const main = document.querySelector('.main-content'); if (main && !main.hasAttribute('role')) { main.setAttribute('role', 'main'); main.setAttribute('aria-label', '主要内容'); } // 添加导航地标 const nav = document.querySelector('.bottom-nav'); if (nav && !nav.hasAttribute('role')) { nav.setAttribute('role', 'navigation'); nav.setAttribute('aria-label', '主导航'); } // 添加区域标识 document.querySelectorAll('.card').forEach((card, index) => { if (!card.hasAttribute('role')) { card.setAttribute('role', 'region'); const title = card.querySelector('.card-title')?.textContent; if (title) { card.setAttribute('aria-labelledby', `card-title-${index}`); const titleElement = card.querySelector('.card-title'); if (titleElement) { titleElement.id = `card-title-${index}`; } } } }); } /** * 关闭模态框 * @param {Element} modal - 模态框元素 */ closeModal(modal) { modal.style.display = 'none'; // 恢复焦点到触发元素 const trigger = document.querySelector('[data-modal-trigger]'); if (trigger) { trigger.focus(); } } } /** * 响应式设计工具类 */ class ResponsiveUtils { constructor() { this.breakpoints = { mobile: 375, tablet: 768, desktop: 1024, }; this.currentBreakpoint = this.getCurrentBreakpoint(); this.init(); } /** * 初始化响应式功能 */ init() { this.setupViewportMeta(); this.setupMediaQueries(); this.setupOrientationChange(); this.addResponsiveClasses(); } /** * 设置viewport元标签 */ setupViewportMeta() { let viewport = document.querySelector('meta[name="viewport"]'); if (!viewport) { viewport = document.createElement('meta'); viewport.name = 'viewport'; document.head.appendChild(viewport); } viewport.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'; } /** * 设置媒体查询监听 */ setupMediaQueries() { Object.entries(this.breakpoints).forEach(([name, width]) => { const mediaQuery = window.matchMedia(`(max-width: ${width}px)`); mediaQuery.addListener((e) => { this.handleBreakpointChange(); }); }); window.addEventListener('resize', () => { this.handleBreakpointChange(); }); } /** * 处理断点变化 */ handleBreakpointChange() { const newBreakpoint = this.getCurrentBreakpoint(); if (newBreakpoint !== this.currentBreakpoint) { this.currentBreakpoint = newBreakpoint; this.addResponsiveClasses(); // 触发自定义事件 const event = new CustomEvent('breakpointChange', { detail: { breakpoint: newBreakpoint }, }); window.dispatchEvent(event); } } /** * 获取当前断点 */ getCurrentBreakpoint() { const width = window.innerWidth; if (width <= this.breakpoints.mobile) return 'mobile'; if (width <= this.breakpoints.tablet) return 'tablet'; return 'desktop'; } /** * 添加响应式类名 */ addResponsiveClasses() { document.body.className = document.body.className .replace(/\b(mobile|tablet|desktop)\b/g, '') .trim(); document.body.classList.add(this.currentBreakpoint); } /** * 设置屏幕方向变化监听 */ setupOrientationChange() { window.addEventListener('orientationchange', () => { setTimeout(() => { this.handleBreakpointChange(); // 修复iOS Safari的viewport问题 if (/iPhone|iPad/.test(navigator.userAgent)) { document.body.style.height = window.innerHeight + 'px'; } }, 100); }); } /** * 获取安全区域内边距 */ getSafeAreaInsets() { const computedStyle = getComputedStyle(document.documentElement); return { top: computedStyle.getPropertyValue('env(safe-area-inset-top)') || '0px', right: computedStyle.getPropertyValue('env(safe-area-inset-right)') || '0px', bottom: computedStyle.getPropertyValue('env(safe-area-inset-bottom)') || '0px', left: computedStyle.getPropertyValue('env(safe-area-inset-left)') || '0px', }; } /** * 是否为移动设备 */ isMobile() { return this.currentBreakpoint === 'mobile'; } /** * 是否为平板设备 */ isTablet() { return this.currentBreakpoint === 'tablet'; } /** * 是否为桌面设备 */ isDesktop() { return this.currentBreakpoint === 'desktop'; } } // 创建全局实例 const accessibilityUtils = new AccessibilityUtils(); const responsiveUtils = new ResponsiveUtils(); // 添加全局样式 const globalStyles = ` /* 高对比度模式 */ .high-contrast { --uni-color-primary: #000000; --uni-bg-color: #ffffff; --uni-text-color: #000000; --uni-text-color-secondary: #333333; --uni-border-color: #000000; } .high-contrast .card { border: 2px solid #000000; background: #ffffff; } /* 大字体模式 */ .large-text { font-size: 120%; } .large-text .card-title { font-size: 120%; } .large-text .service-title { font-size: 120%; } /* 屏幕阅读器模式 */ .screen-reader-mode .decorative { display: none; } /* 键盘导航焦点样式 */ .keyboard-navigation *:focus { outline: 2px solid rgb(93, 135, 255); outline-offset: 2px; } /* 响应式调整 */ @media (max-width: 375px) { .mobile .grid-4 { grid-template-columns: repeat(3, 1fr); } .mobile .service-item { padding: 12px; } .mobile .card { margin: 8px; } } @media (max-width: 320px) { .mobile .grid-4, .mobile .grid-3 { grid-template-columns: 1fr 1fr; } } /* 安全区域适配 */ .page-container { padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom); padding-left: env(safe-area-inset-left); padding-right: env(safe-area-inset-right); } `; // 插入全局样式 const globalStyleSheet = document.createElement('style'); globalStyleSheet.textContent = globalStyles; document.head.appendChild(globalStyleSheet); export { AccessibilityUtils, ResponsiveUtils }; export default { accessibilityUtils, responsiveUtils };