/
Codeboy1
/
lab6
Обзор
Документация
Войти
/
Codeboy1
/
lab6
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
7.html
329 строк
12 KB
Codeboy1
create: 1.html, 2.html, 3.html, 4.html, 5.html, 6.html, 7.html, 8.html, 9.html
01 апр 2026, 14:10
Верифицирован
01 апр 2026, 14:10
b887c38
Код
Авторство
О чём код?
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Функция clear(elem) - удаление содержимого</title> <style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; } .container { background: white; border-radius: 20px; padding: 30px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); } h1 { color: #333; margin-bottom: 10px; font-size: 1.8rem; text-align: center; } .info { background: #e3f2fd; padding: 15px; border-radius: 10px; margin-bottom: 25px; border-left: 4px solid #2196f3; } .info code { background: #fff; padding: 2px 6px; border-radius: 4px; font-family: 'Courier New', monospace; color: #d32f2f; } ol { background: #f8f9fa; padding: 20px 20px 20px 40px; border-radius: 10px; border: 2px solid #e0e0e0; margin: 20px 0; transition: all 0.3s ease; } ol li { padding: 8px; margin: 5px 0; background: white; border-radius: 5px; font-size: 1.1rem; } button { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 24px; font-size: 1rem; border-radius: 8px; cursor: pointer; margin: 10px 10px 10px 0; transition: all 0.3s ease; font-weight: 600; } button:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.2); } button:active { transform: translateY(0); } .btn-reset { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); } .btn-clear { background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); } .status { margin-top: 20px; padding: 10px; border-radius: 8px; font-size: 0.9rem; text-align: center; } .status-empty { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; } .status-full { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; } .code-example { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 8px; font-family: 'Courier New', monospace; margin: 20px 0; overflow-x: auto; } .code-example pre { margin: 0; white-space: pre-wrap; } hr { margin: 20px 0; border: none; border-top: 2px solid #e0e0e0; } </style> </head> <body> <div class="container"> <h1>🧹 Функция clear(elem)</h1> <div class="info"> <strong>📌 Описание:</strong> Функция <code>clear(elem)</code> удаляет всё содержимое из переданного элемента.<br> В данном примере она очищает список с <strong>id="list"</strong>. </div> <ol id="list"> <li>Привет</li> <li>Мир</li> </ol> <div> <button class="btn-clear" onclick="clearList()">🗑️ Очистить список (clear)</button> <button class="btn-reset" onclick="resetList()">🔄 Сбросить список</button> </div> <div id="status" class="status status-full"> ✅ Список содержит элементы </div> <hr> <div class="code-example"> <strong>📝 Код функции:</strong> <pre><code>function clear(elem) { // Способ 1: установка innerHTML в пустую строку elem.innerHTML = ''; // Способ 2: удаление всех дочерних узлов в цикле // while (elem.firstChild) { // elem.removeChild(elem.firstChild); // } // Способ 3: замена элемента на его копию без содержимого // elem.replaceChildren(); // современный способ }</code></pre> </div> <div class="info" style="background: #fef9e6; border-left-color: #ff9800;"> <strong>💡 Примечание:</strong> <ul style="margin: 10px 0 0 20px;"> <li>Функция <code>clear(elem)</code> удаляет ВСЁ содержимое элемента, включая текст и дочерние элементы</li> <li>Сам элемент остается на странице (он не удаляется)</li> <li>Можно использовать несколько способов: <code>innerHTML = ''</code>, <code>removeChild()</code> в цикле, или <code>replaceChildren()</code></li> </ul> </div> </div> <script> // Функция clear - удаляет всё содержимое из elem function clear(elem) { // Способ 1: через innerHTML (простой и быстрый) elem.innerHTML = ''; // Альтернативные способы (закомментированы): // Способ 2: удаление всех дочерних узлов в цикле // while (elem.firstChild) { // elem.removeChild(elem.firstChild); // } // Способ 3: современный метод replaceChildren() (ES2020) // elem.replaceChildren(); } // Функция для очистки списка по id function clearList() { const listElement = document.getElementById('list'); // Проверяем, существует ли элемент if (listElement) { // Вызываем функцию clear clear(listElement); // Обновляем статус updateStatus(); // Показываем уведомление showNotification('Список очищен!', 'success'); } else { showNotification('Элемент не найден!', 'error'); } } // Функция для сброса списка к исходному состоянию function resetList() { const listElement = document.getElementById('list'); if (listElement) { // Очищаем список clear(listElement); // Добавляем исходные элементы const items = ['Привет', 'Мир']; items.forEach(text => { const li = document.createElement('li'); li.textContent = text; listElement.appendChild(li); }); // Обновляем статус updateStatus(); showNotification('Список восстановлен!', 'info'); } } // Функция обновления статуса списка function updateStatus() { const listElement = document.getElementById('list'); const statusDiv = document.getElementById('status'); if (listElement) { const hasChildren = listElement.children.length > 0; if (hasChildren) { statusDiv.className = 'status status-full'; statusDiv.innerHTML = '✅ Список содержит элементы'; } else { statusDiv.className = 'status status-empty'; statusDiv.innerHTML = '⚠️ Список пуст (все элементы удалены)'; } } } // Функция для показа уведомлений (простой alert) function showNotification(message, type) { // Можно использовать alert, но для лучшего UX используем всплывающее сообщение // Для наглядности используем alert (по требованию задания) // alert(message); // Создаем временное всплывающее сообщение const notification = document.createElement('div'); notification.textContent = message; notification.style.cssText = ` position: fixed; top: 20px; right: 20px; background: ${type === 'success' ? '#4caf50' : type === 'error' ? '#f44336' : '#2196f3'}; color: white; padding: 12px 20px; border-radius: 8px; font-size: 14px; z-index: 1000; animation: slideIn 0.3s ease; box-shadow: 0 2px 10px rgba(0,0,0,0.2); `; document.body.appendChild(notification); setTimeout(() => { notification.style.animation = 'slideOut 0.3s ease'; setTimeout(() => notification.remove(), 300); }, 2000); } // Добавляем стили для анимации уведомлений const style = document.createElement('style'); 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); // Инициализация: проверяем статус при загрузке страницы updateStatus(); // Демонстрация работы функции clear на консоли console.log('Функция clear определена. Используйте clearList() для очистки списка'); console.log('Исходный список:', document.getElementById('list')); </script> </body> </html>