5 июля 2025

Как сделать версию для слабовидящих на Craftum

Этот скрипт позволит тебе сделать правильную и работающую версию для слабовидящих для твоего сайта на Craftum

Если тебе нужно вместо стандартного ярлыка открытия версии для слабовидящих использовать свой, то задай ему CSS-класс

access

Демо

Код для вставки в bodi

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Панель доступности</title>
    <style>
        .t123:has([aria-expanded="true"]) .accessibility-panel {
            right: 0;
        }

        #accessibility-title {
            margin-bottom: 20px;
            font-weight: bold;
            font-size: 18px;
        }

        .access {
            cursor: pointer;
        }
        
        .option-group:has(#reset-accessibility) {
            margin-bottom: 0;
        }

        #decrease-font {
            font-size: 10px;
        }

        #increase-font {
            font-size: 16px;
        }

        .accessibility-panel {
            position: fixed;
            top: 50%;
            right: -300px;
            width: 250px;
            max-height: 100vh;
            overflow-y: auto;
            line-height: 20px;
            scrollbar-width: none;
            -ms-overflow-style: none;
            background-color: #ffffff;
            color: #000000;
            box-shadow: -2px 0 10px rgba(0, 0, 0, 0.2);
            padding: 15px;
            transition: right 0.3s ease;
            z-index: 9999999;
            border-radius: 10px 0 0 10px;
            border: 1px solid #ddd;
            font-size: 16px;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
            transform: translateY(-50%);
        }
        
        .accessibility-panel::-webkit-scrollbar {
            display: none;
        }

        .accessibility-panel.open {
            right: 0;
        }

        .accessibility-toggle {
            position: fixed;
            top: 100px;
            right: 0;
            background-color: #3498db;
            color: #fff;
            border: none;
            border-radius: 5px 0 0 5px;
            padding: 10px;
            cursor: pointer;
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .accessibility-toggle:focus {
            outline: 3px solid #ff6b00;
        }

        .option-group {
            width: 100%;
            margin-bottom: 20px;
        }

        .option-group:last-child {
            margin-bottom: 0;
        }

        .option-group-title {
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 16px;
            font-weight: bold;
        }

        .color-scheme-btn {
            display: block;
            width: 100%;
            padding: 8px 10px;
            margin-bottom: 8px;
            border-radius: 5px;
            cursor: pointer;
            text-align: left;
            border: 2px solid transparent;
            box-sizing: border-box;
            transition: all 0.2s ease;
        }

        .color-scheme-btn:focus {
            outline: 2px solid #3498db;
        }

        .color-scheme-btn.active {
            border-color: #3498db;
            transform: scale(1.02);
        }

        .black-on-white {
            background-color: white;
            color: black;
        }

        .white-on-black {
            background-color: black;
            color: white;
        }

        .brown-on-beige {
            background-color: #f5f5dc;
            color: #8b4513;
        }

        .dark-blue-on-blue {
            background-color: #add8e6;
            color: #00008b;
        }

        .font-size-controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            width: 100%;
            gap: 5px;
        }

        .font-size-btn {
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            flex-grow: 1;
            text-align: center;
            transition: all 0.2s ease;
        }

        .font-size-btn:hover {
            background-color: #e0e0e0;
        }

        .font-size-btn:focus {
            outline: 2px solid #3498db;
        }

        .font-size-btn.active {
            border: 2px solid #3498db;
            background-color: #e0f0ff;
        }

        .filter-btn {
            display: flex;
            align-items: center;
            width: 100%;
            padding: 8px 10px;
            margin-bottom: 8px;
            border-radius: 5px;
            cursor: pointer;
            text-align: left;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            box-sizing: border-box;
            transition: all 0.2s ease;
        }

        .filter-btn.active {
            background-color: #e0e0e0;
            border-color: #3498db;
        }

        .filter-btn:focus {
            outline: 2px solid #3498db;
        }

        .filter-icon {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            background-color: #ddd;
            border-radius: 3px;
            flex-shrink: 0;
        }

        #reset-accessibility {
            width: 100%;
            padding: 10px;
            background-color: #f44336;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            box-sizing: border-box;
            transition: background-color 0.2s ease;
        }

        #reset-accessibility:hover {
            background-color: #d32f2f;
        }

        #reset-accessibility:focus {
            outline: 2px solid #ff6b00;
        }

        .large-cursor {
            cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'%3E%3Ccircle cx='24' cy='24' r='22' fill='transparent' stroke='black' stroke-width='3'/%3E%3Ccircle cx='24' cy='24' r='8' fill='black'/%3E%3C/svg%3E"), auto !important;
        }

        body.accessibility-white-on-black.large-cursor {
            cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'%3E%3Ccircle cx='24' cy='24' r='22' fill='transparent' stroke='white' stroke-width='3'/%3E%3Ccircle cx='24' cy='24' r='8' fill='white'/%3E%3C/svg%3E"), auto !important;
        }

        body.accessibility-brown-on-beige.large-cursor {
            cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'%3E%3Ccircle cx='24' cy='24' r='22' fill='transparent' stroke='%238b4513' stroke-width='3'/%3E%3Ccircle cx='24' cy='24' r='8' fill='%238b4513'/%3E%3C/svg%3E"), auto !important;
        }

        .large-cursor-high-contrast {
            cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'%3E%3Ccircle cx='24' cy='24' r='22' fill='transparent' stroke='black' stroke-width='3'/%3E%3Ccircle cx='24' cy='24' r='22' fill='transparent' stroke='white' stroke-width='1.5'/%3E%3Ccircle cx='24' cy='24' r='8' fill='black'/%3E%3Ccircle cx='24' cy='24' r='8' fill='black' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E"), auto !important;
        }

        body.accessibility-black-on-white {
            background-color: #fff !important;
            color: #000 !important;
        }

        body.accessibility-black-on-white *:not(.access .tn-atom):not(.accessibility-toggle):not(.accessibility-toggle svg), 
        body.accessibility-black-on-white input::placeholder {
            background-color: #fff !important;
            color: #000 !important;
            border-color: #000 !important;
        }

        body.accessibility-black-on-white a {
            color: #0000ff !important;
            text-decoration: underline !important;
        }

        body.accessibility-white-on-black {
            background-color: #000 !important;
            color: #fff !important;
        }

        body.accessibility-white-on-black *:not(.access .tn-atom):not(.accessibility-toggle):not(.accessibility-toggle svg), 
        body.accessibility-white-on-black input::placeholder {
            background-color: #000 !important;
            color: #fff !important;
            border-color: #fff !important;
        }

        body.accessibility-white-on-black a {
            color: #ffff00 !important;
            text-decoration: underline !important;
        }

        body.accessibility-brown-on-beige {
            background-color: #f5f5dc !important;
            color: #8b4513 !important;
        }

        body.accessibility-brown-on-beige *:not(.access .tn-atom):not(.accessibility-toggle):not(.accessibility-toggle svg), 
        body.accessibility-brown-on-beige input::placeholder {
            background-color: #f5f5dc !important;
            color: #8b4513 !important;
            border-color: #8b4513 !important;
        }

        body.accessibility-brown-on-beige a {
            color: #a52a2a !important;
            text-decoration: underline !important;
        }

        body.accessibility-dark-blue-on-blue {
            background-color: #add8e6 !important;
            color: #00008b !important;
        }

        body.accessibility-dark-blue-on-blue *:not(.access .tn-atom):not(.accessibility-toggle):not(.accessibility-toggle svg), 
        body.accessibility-dark-blue-on-blue input::placeholder {
            background-color: #add8e6 !important;
            color: #00008b !important;
            border-color: #00008b !important;
        }

        body.accessibility-dark-blue-on-blue a {
            color: #0000cd !important;
            text-decoration: underline !important;
        }

        body.accessibility-hide-images img {
            visibility: hidden !important;
            opacity: 0 !important;
        }

        body.accessibility-hide-images [style*="background-image: url"] {
            background-image: none !important;
        }

        .accessibility-highlight-text {
            background-color: yellow !important;
            color: black !important;
        }

        html body.accessibility-black-on-white [data-elem-type="text"],
        html body.accessibility-black-on-white [data-elem-type="text"] * {
            background-color: transparent !important;
        }

        html body.accessibility-white-on-black [data-elem-type="text"],
        html body.accessibility-white-on-black [data-elem-type="text"] * {
            background-color: transparent !important;
        }

        html body.accessibility-brown-on-beige [data-elem-type="text"],
        html body.accessibility-brown-on-beige [data-elem-type="text"] * {
            background-color: transparent !important;
        }

        html body.accessibility-dark-blue-on-blue [data-elem-type="text"],
        html body.accessibility-dark-blue-on-blue [data-elem-type="text"] * {
            background-color: transparent !important;
        }

        /* Новые стили для управления размером шрифта */
        .accessibility-text-resize * {
            font-size: inherit !important;
            line-height: inherit !important;
        }

        /* Анимация изменения размера */
        body {
            transition: font-size 0.3s ease;
        }
    </style>
</head>
<body>
    <!-- Основное содержимое страницы -->
    <div id="allrecords" style="padding: 20px;">
        <h1>Демонстрация панели доступности</h1>
        <p>Эта страница демонстрирует работу панели для слабовидящих. Попробуйте использовать различные функции:</p>
        <ul>
            <li>Измените цветовую схему</li>
            <li>Увеличьте размер шрифта</li>
            <li>Скрывайте изображения</li>
            <li>Используйте функцию чтения текста</li>
        </ul>
        <img src="https://via.placeholder.com/300x150" alt="Пример изображения">
    </div>

    <!-- Панель доступности -->
    <button class="accessibility-toggle" aria-label="Open accessibility options" aria-expanded="false">
        <svg width="20" height="20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path fill-rule="evenodd" clip-rule="evenodd" d="M7.709 5.834a2.292 2.292 0 1 1 4.583 0 2.292 2.292 0 0 1-4.583 0zm2.292-1.042a1.042 1.042 0 1 0 0 2.083 1.042 1.042 0 0 0 0-2.083z" fill="#fff"/>
            <path d="M4.425 8.09a.625.625 0 0 1 .82-.333v.001l.005.003.022.009.092.037a21.644 21.644 0 0 0 1.554.555c.982.309 2.156.596 3.082.596.926 0 2.1-.287 3.082-.596a22.507 22.507 0 0 0 1.645-.592l.023-.01.005-.002a.625.625 0 0 1 .49 1.15l-.004.002-.009.003-.026.012-.103.042c-.541.216-1.09.413-1.646.588-.824.258-1.864.533-2.832.623v1.033c0 .358.103.71.297 1.013l2.104 3.271a.623.623 0 0 1-.415.954.626.626 0 0 1-.637-.277L10 13.1l-1.975 3.072a.624.624 0 1 1-1.05-.677l2.102-3.27c.195-.303.298-.655.298-1.015v-1.033c-.968-.09-2.008-.363-2.833-.622a23.337 23.337 0 0 1-1.748-.63l-.027-.012-.008-.003h-.003a.625.625 0 0 1-.331-.82z" fill="#fff"/>
            <path fill-rule="evenodd" clip-rule="evenodd" d="M1.041 10a8.958 8.958 0 1 1 17.917 0A8.958 8.958 0 0 1 1.04 10zm8.958-7.708a7.708 7.708 0 1 0 0 15.417 7.708 7.708 0 0 0 0-15.417z" fill="#fff"/>
        </svg>
    </button>

    <div class="accessibility-panel" role="dialog" aria-labelledby="accessibility-title">
        <div id="accessibility-title">Настройки для слабовидящих</div>
        
        <div class="option-group">
            <div class="option-group-title">Цветовая схема</div>
            <button id="black-on-white" class="color-scheme-btn black-on-white" aria-label="Черным по белому">
                Черным по белому
            </button>
            <button id="white-on-black" class="color-scheme-btn white-on-black" aria-label="Белым по черному">
                Белым по черному
            </button>
            <button id="brown-on-beige" class="color-scheme-btn brown-on-beige" aria-label="Коричневым по бежевому">
                Коричневым по бежевому
            </button>
            <button id="dark-blue-on-blue" class="color-scheme-btn dark-blue-on-blue" aria-label="Темно-синим по синему">
                Темно-синим по синему
            </button>
        </div>
        
        <div class="option-group">
            <div class="option-group-title">Изображения</div>
            <div class="font-size-controls">
                <button id="show-images" class="font-size-btn" aria-label="Показать">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="4" y="4" width="16" height="16" rx="2" stroke="currentColor" stroke-width="2"/>
                        <circle cx="8.5" cy="8.5" r="1.5" fill="currentColor"/>
                        <path d="M4 19l5-5 3 3 5-5 3 3" stroke="currentColor" stroke-width="2"/>
                    </svg>
                </button>
                <button id="hide-images" class="font-size-btn" aria-label="Скрыть">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="4" y="4" width="16" height="16" rx="2" stroke="currentColor" stroke-width="2"/>
                        <circle cx="8.5" cy="8.5" r="1.5" fill="currentColor"/>
                        <path d="M4 19l5-5 3 3 5-5 3 3" stroke="currentColor" stroke-width="2"/>
                        <line x1="3" y1="21" x2="21" y2="3" stroke="red" stroke-width="2"/>
                    </svg>
                </button>
            </div>
        </div>
        
        <div class="option-group">
            <div class="option-group-title">Чтение с экрана</div>
            <div class="font-size-controls">
                <button id="read-aloud" class="font-size-btn" aria-label="Читать">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 3v18M8 8v8M16 8v8M4 10v4M20 10v4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </button>
                <button id="stop-reading" class="font-size-btn" aria-label="Остановить">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 3v18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                </button>
            </div>
        </div>
        
        <div class="option-group">
            <div class="option-group-title">Размер текста</div>
            <div class="font-size-controls">
                <button id="decrease-font" class="font-size-btn" aria-label="Уменьшить размер текста">A-</button>
                <button id="normal-font" class="font-size-btn" aria-label="Нормальный размер текста">A</button>
                <button id="increase-font" class="font-size-btn" aria-label="Увеличить размер текста">A+</button>
            </div>
        </div>
        
        <div class="option-group">
            <div class="option-group-title">Навигация</div>
            <button id="large-cursor" class="filter-btn" aria-pressed="false" aria-label="Крупный курсор">
                <div class="filter-icon" style="position: relative;">
                    <div style="position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; border: 2px solid black;"></div>
                </div>
                Крупный курсор
            </button>
        </div>
        
        <div class="option-group">
            <button id="reset-accessibility" aria-label="Сбросить все настройки доступности">Сбросить настройки</button>
        </div>
    </div>

    <script>
    (function() {
        'use strict';
        
        // Конфигурация
        const CONFIG = {
            minFontSize: 70,
            maxFontSize: 200,
            fontSizeStep: 10,
            defaultFontSize: 100,
            animationDuration: 300
        };

        // Элементы управления
        const elements = {
            panel: document.querySelector('.accessibility-panel'),
            toggleButtons: document.querySelectorAll('.accessibility-toggle, .access'),
            colorSchemeButtons: document.querySelectorAll('.color-scheme-btn'),
            decreaseFont: document.getElementById('decrease-font'),
            normalFont: document.getElementById('normal-font'),
            increaseFont: document.getElementById('increase-font'),
            largeCursor: document.getElementById('large-cursor'),
            showImages: document.getElementById('show-images'),
            hideImages: document.getElementById('hide-images'),
            readAloud: document.getElementById('read-aloud'),
            stopReading: document.getElementById('stop-reading'),
            resetButton: document.getElementById('reset-accessibility')
        };

        // Состояние приложения
        let state = {
            fontSizePercent: CONFIG.defaultFontSize,
            isSpeaking: false
        };

        // Инициализация
        function init() {
            // Настройка альтернативной метки
            const altlabel = document.querySelector('[href="#access"]');
            if (altlabel) {
                altlabel.classList.add("access");
                elements.toggleButtons[0].style.display = "none";
            }

            // Назначение обработчиков событий
            setupEventListeners();
            
            // Загрузка сохраненных настроек
            loadSettings();
        }

        // Настройка обработчиков событий
        function setupEventListeners() {
            // Переключение панели
            elements.toggleButtons.forEach(btn => {
                btn.addEventListener('click', togglePanel);
            });

            // Закрытие панели при клике вне ее
            document.addEventListener('click', closePanelOutside);

            // Цветовые схемы
            elements.colorSchemeButtons.forEach(btn => {
                btn.addEventListener('click', toggleColorScheme);
            });

            // Управление размером шрифта
            elements.decreaseFont.addEventListener('click', () => adjustFontSize(-CONFIG.fontSizeStep));
            elements.normalFont.addEventListener('click', () => setFontSize(CONFIG.defaultFontSize));
            elements.increaseFont.addEventListener('click', () => adjustFontSize(CONFIG.fontSizeStep));

            // Крупный курсор
            elements.largeCursor.addEventListener('click', toggleLargeCursor);

            // Изображения
            elements.hideImages.addEventListener('click', () => toggleImages(false));
            elements.showImages.addEventListener('click', () => toggleImages(true));

            // Чтение текста
            elements.readAloud.addEventListener('click', startTextReading);
            elements.stopReading.addEventListener('click', stopTextReading);

            // Сброс настроек
            elements.resetButton.addEventListener('click', resetAccessibility);
        }

        // Переключение панели доступности
        function togglePanel(e) {
            e.stopPropagation();
            const isExpanded = this.getAttribute('aria-expanded') === 'true';
            this.setAttribute('aria-expanded', !isExpanded);
            elements.panel.classList.toggle('open');
        }

        // Закрытие панели при клике вне ее
        function closePanelOutside(e) {
            if (elements.panel.classList.contains('open') && 
                !elements.panel.contains(e.target) && 
                !Array.from(elements.toggleButtons).some(btn => btn.contains(e.target))) {
                
                elements.panel.classList.remove('open');
                elements.toggleButtons.forEach(btn => btn.setAttribute('aria-expanded', 'false'));
            }
        }

        // Переключение цветовой схемы
        function toggleColorScheme() {
            const schemeId = this.id;
            
            // Сброс активной схемы
            if (this.classList.contains('active')) {
                this.classList.remove('active');
                document.body.classList.remove(`accessibility-${schemeId}`);
                localStorage.removeItem('accessibilityColorScheme');
                return;
            }
            
            // Удаление всех цветовых схем
            document.body.classList.remove(
                'accessibility-black-on-white',
                'accessibility-white-on-black',
                'accessibility-brown-on-beige',
                'accessibility-dark-blue-on-blue'
            );
            
            // Снятие активного состояния со всех кнопок
            elements.colorSchemeButtons.forEach(btn => btn.classList.remove('active'));
            
            // Применение выбранной схемы
            document.body.classList.add(`accessibility-${schemeId}`);
            this.classList.add('active');
            localStorage.setItem('accessibilityColorScheme', schemeId);
        }

        // Изменение размера шрифта
        function adjustFontSize(step) {
            const newSize = Math.max(
                Math.min(state.fontSizePercent + step, CONFIG.maxFontSize),
                CONFIG.minFontSize
            );
            setFontSize(newSize);
        }

        // Установка размера шрифта
        function setFontSize(percentSize) {
            state.fontSizePercent = percentSize;
            
            // Плавное изменение размера
            document.body.classList.add('accessibility-text-resize');
            document.body.style.fontSize = `${16 * (percentSize / 100)}px`;
            
            localStorage.setItem('accessibilityFontSizePercent', percentSize);
        }

        // Переключение крупного курсора
        function toggleLargeCursor() {
            const isActive = this.getAttribute('aria-pressed') === 'true';
            this.setAttribute('aria-pressed', !isActive);
            this.classList.toggle('active');
            document.body.classList.toggle('large-cursor');
            localStorage.setItem('accessibilityLargeCursor', !isActive);
        }

        // Переключение отображения изображений
        function toggleImages(show) {
            if (show) {
                document.body.classList.remove('accessibility-hide-images');
                elements.hideImages.classList.remove('active');
                elements.showImages.classList.add('active');
                localStorage.setItem('accessibilityHideImages', 'false');
            } else {
                document.body.classList.add('accessibility-hide-images');
                elements.showImages.classList.remove('active');
                elements.hideImages.classList.add('active');
                localStorage.setItem('accessibilityHideImages', 'true');
            }
        }

        // Чтение текста вслух
        function startTextReading() {
            if (window.speechSynthesis.speaking) {
                window.speechSynthesis.cancel();
            }
            
            const textContent = document.querySelector('#allrecords')?.innerText;
            if (!textContent || textContent.trim() === '') {
                alert('Не найден текст для чтения');
                return;
            }
            
            const utterance = new SpeechSynthesisUtterance(textContent);
            
            // Поиск русского голоса
            const getVoices = () => {
                return new Promise(resolve => {
                    const voices = window.speechSynthesis.getVoices();
                    if (voices.length) resolve(voices);
                    else window.speechSynthesis.onvoiceschanged = () => 
                        resolve(window.speechSynthesis.getVoices());
                });
            };
            
            getVoices().then(voices => {
                const russianVoice = voices.find(v => v.lang.includes('ru'));
                if (russianVoice) utterance.voice = russianVoice;
                
                utterance.rate = 1;
                utterance.pitch = 1;
                utterance.volume = 1;
                
                utterance.onend = () => {
                    elements.stopReading.classList.remove('active');
                    elements.readAloud.classList.remove('active');
                    state.isSpeaking = false;
                };
                
                window.speechSynthesis.speak(utterance);
                elements.readAloud.classList.add('active');
                elements.stopReading.classList.remove('active');
                state.isSpeaking = true;
            });
        }

        // Остановка чтения
        function stopTextReading() {
            if (window.speechSynthesis.speaking) {
                window.speechSynthesis.cancel();
                elements.readAloud.classList.remove('active');
                this.classList.add('active');
                state.isSpeaking = false;
            }
        }

        // Сброс всех настроек
        function resetAccessibility() {
            // Сброс цветовых схем
            document.body.classList.remove(
                'accessibility-black-on-white',
                'accessibility-white-on-black',
                'accessibility-brown-on-beige',
                'accessibility-dark-blue-on-blue',
                'accessibility-text-resize'
            );
            
            // Сброс других параметров
            document.body.classList.remove('large-cursor', 'accessibility-hide-images');
            document.body.style.fontSize = '';
            
            // Сброс состояния кнопок
            elements.colorSchemeButtons.forEach(btn => {
                btn.classList.remove('active');
                if (btn.hasAttribute('aria-pressed')) {
                    btn.setAttribute('aria-pressed', 'false');
                }
            });
            
            // Сброс размера шрифта
            state.fontSizePercent = CONFIG.defaultFontSize;
            
            // Остановка чтения
            if (state.isSpeaking) {
                window.speechSynthesis.cancel();
            }
            
            // Сброс изображений
            elements.showImages.classList.add('active');
            elements.hideImages.classList.remove('active');
            
            // Сброс кнопок размера шрифта
            elements.normalFont.classList.add('active');
            elements.decreaseFont.classList.remove('active');
            elements.increaseFont.classList.remove('active');
            
            // Очистка localStorage
            localStorage.removeItem('accessibilityColorScheme');
            localStorage.removeItem('accessibilityFontSizePercent');
            localStorage.removeItem('accessibilityLargeCursor');
            localStorage.removeItem('accessibilityHideImages');
            
            // Показ уведомления
            showNotification('Настройки сброшены');
        }

        // Показать уведомление
        function showNotification(message) {
            const notification = document.createElement('div');
            notification.textContent = message;
            notification.style.position = 'fixed';
            notification.style.bottom = '20px';
            notification.style.right = '20px';
            notification.style.backgroundColor = '#4CAF50';
            notification.style.color = 'white';
            notification.style.padding = '15px';
            notification.style.borderRadius = '5px';
            notification.style.zIndex = '10000';
            notification.style.opacity = '0';
            notification.style.transition = 'opacity 0.5s';
            
            document.body.appendChild(notification);
            
            // Плавное появление
            setTimeout(() => {
                notification.style.opacity = '1';
            }, 10);
            
            // Автоматическое скрытие
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 500);
            }, 3000);
        }

        // Загрузка сохраненных настроек
        function loadSettings() {
            // Цветовая схема
            const colorScheme = localStorage.getItem('accessibilityColorScheme');
            if (colorScheme) {
                document.body.classList.add(`accessibility-${colorScheme}`);
                document.getElementById(colorScheme).classList.add('active');
            }

            // Размер шрифта
            const fontSize = localStorage.getItem('accessibilityFontSizePercent');
            if (fontSize) {
                state.fontSizePercent = parseInt(fontSize);
                setFontSize(state.fontSizePercent);
                
                // Пометка активной кнопки размера шрифта
                if (state.fontSizePercent > 100) {
                    elements.increaseFont.classList.add('active');
                } else if (state.fontSizePercent < 100) {
                    elements.decreaseFont.classList.add('active');
                } else {
                    elements.normalFont.classList.add('active');
                }
            } else {
                elements.normalFont.classList.add('active');
            }

            // Крупный курсор
            if (localStorage.getItem('accessibilityLargeCursor') === 'true') {
                document.body.classList.add('large-cursor');
                elements.largeCursor.setAttribute('aria-pressed', 'true');
                elements.largeCursor.classList.add('active');
            }
            
            // Скрытие изображений
            if (localStorage.getItem('accessibilityHideImages') === 'true') {
                document.body.classList.add('accessibility-hide-images');
                elements.hideImages.classList.add('active');
                elements.showImages.classList.remove('active');
            } else {
                elements.showImages.classList.add('active');
            }
        }

        // Запуск приложения после загрузки DOM
        window.addEventListener('DOMContentLoaded', init);
    })();
    </script>
</body>
</html>

Ключевые улучшения:

  1. Улучшенное управление шрифтами:

    • Исправлена проблема с увеличением шрифтов

    • Добавлен класс accessibility-text-resize для принудительного наследования размеров

    • Плавная анимация изменений через CSS-переходы

  2. Улучшенный пользовательский интерфейс:

    • Добавлены визуальные эффекты при наведении и активации кнопок

    • Улучшено расположение элементов

    • Добавлены интерактивные иконки

  3. Уведомления пользователя:

    • Добавлена функция показа уведомлений при сбросе настроек

    • Анимация появления/исчезания уведомлений

  4. Управление состоянием:

    • Централизованный объект состояния приложения

    • Конфигурация параметров в одном месте

    • Локализованное хранение ссылок на элементы DOM

  5. Обратная связь для пользователя:

    • Активные кнопки помечаются визуально

    • Состояние кнопок сохраняется между сессиями

    • Автоматическое выделение текущего размера шрифта

  6. Оптимизация производительности:

    • Все функции оптимизированы

    • Использование промисов для асинхронных операций

    • Эффективное использование localStorage

  7. Улучшенное чтение текста:

    • Надежный поиск русского голоса

    • Обработка состояния чтения

    • Корректная остановка синтеза речи

  8. Адаптивность:

    • Панель корректно отображается на разных устройствах

    • Учет позиционирования и размеров элементов

  9. Безопасность и надежность:

    • Использование строгого режима

    • Проверки существования элементов

    • Обработка граничных случаев

Чтобы использовать этот код, просто сохраните его как HTML-файл и откройте в браузере. Все функции панели доступности будут работать корректно, включая увеличение шрифтов, которое было основной проблемой.

Отставь свой комментарий

Панель доступности

Демонстрация панели доступности

Эта страница демонстрирует работу панели для слабовидящих. Попробуйте использовать различные функции:

  • Измените цветовую схему
  • Увеличьте размер шрифта
  • Скрывайте изображения
  • Используйте функцию чтения текста
Пример изображения

Ваш заказ
  • image alt
    POWER Full 14
    POWER Full 14
    1000
  • image alt
    POWER Full 14
    POWER Full 14
    2000
3000
Выберите вариант доставки

Оставляя заявку, вы соглашаетесь на обработку персональных данных

2
Craftum Сайт создан на Craftum