/
RoditelevVV
/
web-static-labs
Обзор
Документация
Войти
/
RoditelevVV
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
html/lab5/task7/script.js
257 строк
9 KB
karpov
finish lab3, lab4
12 мар 2026, 08:19
12 мар 2026, 08:19
74cd197
Код
Авторство
О чём код?
class MultiplicationTable { constructor() { this.currentTable = null; this.initializeElements(); this.setupEventListeners(); } initializeElements() { // Элементы настроек this.rowsInput = document.getElementById('rowsInput'); this.colsInput = document.getElementById('colsInput'); this.createTableBtn = document.getElementById('createTableBtn'); // Элементы таблицы this.multiplicationTable = document.getElementById('multiplicationTable'); this.emptyState = document.getElementById('emptyState'); this.tableSize = document.getElementById('tableSize'); // Элементы модального окна this.cellModal = document.getElementById('cellModal'); this.closeModal = document.getElementById('closeModal'); this.modalRow = document.getElementById('modalRow'); this.modalCol = document.getElementById('modalCol'); this.modalExpression = document.getElementById('modalExpression'); this.modalResult = document.getElementById('modalResult'); } setupEventListeners() { // Кнопка создания таблицы this.createTableBtn.addEventListener('click', () => { this.createTable(); }); // Ввод по Enter в полях this.rowsInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { this.createTable(); } }); this.colsInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { this.createTable(); } }); // Закрытие модального окна this.closeModal.addEventListener('click', () => { this.closeCellModal(); }); // Закрытие модального окна по клику вне его this.cellModal.addEventListener('click', (e) => { if (e.target === this.cellModal) { this.closeCellModal(); } }); // Закрытие модального окна по Escape document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && this.cellModal.style.display === 'block') { this.closeCellModal(); } }); } createTable() { const rows = parseInt(this.rowsInput.value); const cols = parseInt(this.colsInput.value); // Валидация ввода if (!this.validateInput(rows, cols)) { return; } // Создаем таблицу this.generateTable(rows, cols); this.updateTableInfo(rows, cols); this.hideEmptyState(); this.showNotification(`Таблица ${rows}×${cols} создана!`, 'success'); } validateInput(rows, cols) { if (isNaN(rows) || isNaN(cols)) { this.showError('Введите корректные числа'); return false; } if (rows < 1 || rows > 20 || cols < 1 || cols > 20) { this.showError('Числа должны быть в диапазоне от 1 до 20'); return false; } return true; } generateTable(rows, cols) { this.multiplicationTable.innerHTML = ''; this.currentTable = { rows, cols }; // Создаем заголовочную строку const headerRow = this.createTableRow(true); headerRow.appendChild(this.createTableCell('', 'header-cell')); // Пустая ячейка в углу for (let col = 1; col <= cols; col++) { headerRow.appendChild(this.createTableCell(col, 'header-cell')); } this.multiplicationTable.appendChild(headerRow); // Создаем строки с данными for (let row = 1; row <= rows; row++) { const tableRow = this.createTableRow(); // Добавляем заголовочную ячейку для строки tableRow.appendChild(this.createTableCell(row, 'header-cell')); // Добавляем ячейки с результатами умножения for (let col = 1; col <= cols; col++) { const result = row * col; const cell = this.createTableCell(result, 'data-cell'); cell.dataset.row = row; cell.dataset.col = col; cell.dataset.result = result; // Обработчик клика для открытия модального окна cell.addEventListener('click', () => { this.openCellModal(row, col, result); }); tableRow.appendChild(cell); } this.multiplicationTable.appendChild(tableRow); } } createTableRow(isHeader = false) { const row = document.createElement('div'); row.className = 'table-row'; if (isHeader) { row.classList.add('header-row'); } return row; } createTableCell(content, className = '') { const cell = document.createElement('div'); cell.className = `table-cell ${className}`; cell.textContent = content; return cell; } openCellModal(row, col, result) { this.modalRow.textContent = row; this.modalCol.textContent = col; this.modalExpression.textContent = `${row} × ${col}`; this.modalResult.textContent = result; this.cellModal.style.display = 'block'; document.body.style.overflow = 'hidden'; // Блокируем прокрутку фона } closeCellModal() { this.cellModal.style.display = 'none'; document.body.style.overflow = 'auto'; // Восстанавливаем прокрутку } updateTableInfo(rows, cols) { this.tableSize.textContent = `${rows}×${cols}`; } hideEmptyState() { this.emptyState.style.display = 'none'; } showEmptyState() { this.emptyState.style.display = 'flex'; } showNotification(message, type = 'info') { const notification = document.createElement('div'); notification.className = `notification ${type}`; notification.textContent = message; notification.style.cssText = ` position: fixed; top: 20px; right: 20px; padding: 15px 20px; border-radius: 8px; color: white; font-weight: 500; z-index: 1000; animation: slideIn 0.3s ease-out; max-width: 300px; `; if (type === 'success') { notification.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)'; } else if (type === 'error') { notification.style.background = 'linear-gradient(135deg, #ff416c, #ff4b2b)'; } else { notification.style.background = 'linear-gradient(135deg, #3498db, #2980b9)'; } document.body.appendChild(notification); setTimeout(() => { notification.style.animation = 'slideOut 0.3s ease-in'; setTimeout(() => { if (notification.parentNode) { notification.parentNode.removeChild(notification); } }, 300); }, 3000); // Добавляем стили для анимаций если их нет if (!document.querySelector('#notification-styles')) { const style = document.createElement('style'); style.id = 'notification-styles'; style.textContent = ` @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes slideOut { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } } `; document.head.appendChild(style); } } showError(message) { this.showNotification(message, 'error'); } } // Инициализация таблицы умножения при загрузке страницы document.addEventListener('DOMContentLoaded', () => { new MultiplicationTable(); });