Для улучшения дизайна и анимаций вашего HTML-документа вы можете применить следующие улучшения и изменения:
- Использование CSS-переменных: Это обеспечит более легкое изменение цветовой схемы в будущем.
- Улучшение стиля кнопок: Добавим более плавные анимации и улучшенные стили для удобства пользователей.
- Эффекты наведения для элементов интерфейса: Это сделает интерфейс более интерактивным.
- Добавление анимации для появления содержимого: Сюда можно добавить небольшие анимации для улучшенной визуальной обратной связи.
- Модальное окно: Добавим плавную анимацию для открытия и закрытия.
Вот обновленный фрагмент кода:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>iOS Стиль Википедии</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=Raleway:wght@400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha384-k6RqeWeci5ZR/Lv4MR0sA0FfDOM4l7n6n8D7G7xY4b5y5G5zC5g5E6z5Wl4n6c" crossorigin="anonymous">
<style>
:root {
--primary-color: #007aff;
--secondary-color: #e7e7e7;
--background-color: #f7f9fc;
--text-color: #333;
--highlight-color: #e7f3ff;
--border-radius: 12px;
}
body {
font-family: 'Inter', 'Raleway', sans-serif;
margin: 0;
padding: 0;
background-color: var(--background-color);
display: flex;
flex-direction: column;
min-height: 100vh; /* Ensure full height */
}
header {
background-color: var(--primary-color);
padding: 20px;
text-align: center;
border-radius: var(--border-radius) var(--border-radius) 0 0;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}
.header-title {
font-size: 28px;
color: white;
}
.navbar {
display: flex;
justify-content: center;
background-color: var(--secondary-color);
padding: 10px;
border-radius: var(--border-radius);
margin-bottom: 20px;
}
.nav-item {
margin: 0 15px;
cursor: pointer;
text-decoration: none;
color: var(--text-color);
position: relative;
}
.nav-item::after {
content: '';
display: block;
height: 2px;
background: var(--primary-color);
position: absolute;
bottom: -5px;
right: 0;
left: 50%;
transform: translateX(-50%);
transition: opacity 0.3s, left 0.3s, right 0.3s;
opacity: 0;
}
.nav-item:hover::after {
opacity: 1;
left: 0;
right: 0;
}
.container {
display: flex;
flex: 1;
max-width: 1200px;
margin: 20px auto;
padding: 10px;
}
.content {
flex: 1;
background-color: white;
padding: 20px;
border-radius: var(--border-radius);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
animation: fadeIn 0.5s ease-in-out;
}
h1 {
font-size: 24px;
}
p {
font-size: 16px;
color: var(--text-color);
line-height: 1.6;
}
.highlight {
background-color: var(--highlight-color);
padding: 5px;
border-radius: 8px;
display: inline-block;
}
.search-section {
margin-bottom: 20px;
}
.search-section input {
padding: 12px;
width: calc(80% - 22px);
font-size: 16px;
margin-right: 10px;
border-radius: var(--border-radius);
border: 1px solid #ddd;
}
.search-section button {
padding: 12px;
font-size: 16px;
background-color: var(--primary-color);
color: white;
border-radius: var(--border-radius);
cursor: pointer;
transition: background-color 0.3s ease;
}
.search-section button:hover {
background-color: #005bb5;
}
button {
transition: background-color 0.3s ease, transform 0.3s ease;
}
button:hover {
transform: translateY(-2px);
}
footer {
background-color: white;
text-align: center;
padding: 20px;
font-size: 14px;
color: #808080;
margin-top: auto; /* Stick footer to the bottom */
}
.toggle-content {
display: none;
margin-top: 10px;
padding-left: 15px;
}
.info-block {
background-color: #f9f9f9;
border-radius: var(--border-radius);
padding: 15px;
margin-top: 10px;
box-shadow: inset rgba(0,0,0,0.1) -1px -1px, inset rgba(255,255,255,0.5) -1px -1px;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
border-radius: var(--border-radius);
overflow: hidden;
font-size: 14px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 8px;
text-align: left;
}
th {
background-color: #f4f4f4;
font-family: 'Inter', sans-serif;
}
.loading {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-20px); }
to { opacity: 1; transform: translateY(0); }
}
.result-item {
animation-name: fadeIn;
animation-duration: 0.5s;
animation-fill-mode: forwards;
}
.image-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.image-container img {
border-radius: var(--border-radius);
cursor: pointer;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.image-container img:hover {
transform: scale(1.05);
box-shadow: rgba(0, 123, 255, 0.5) -2px -2px, rgba(255, 255, 255, 0.9) -2px -2px inset;
}
.modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
border-radius: var(--border-radius);
box-shadow: rgba(0, 0, 0, 0.2) 0px 14px 28px, rgba(0, 0, 0, 0.2) 0px 10px 10px;
z-index: 1000;
width: 80%;
max-width: 600px;
animation: modalFadeIn 0.5s ease-in-out;
}
@keyframes modalFadeIn {
from { opacity: 0; transform: translate(-50%, -60%); }
to { opacity: 1; transform: translate(-50%, -50%); }
}
.modal img {
width: 100%;
height: auto;
border-radius: var(--border-radius);
}
.modal-close {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
font-size: 24px;
}
</style>
</head>
<body>
<header>
<div class="header-title">РУВИКИ</div>
</header>
<!-- Навигационная панель -->
<div class="navbar">
<a class="nav-item" href="#">Главная</a>
<a class="nav-item" href="#">Избранное</a>
<a class="nav-item" href="#">Настройки</a>
</div>
<div class="container">
<div class="content">
<h1>Поиск информации</h1>
<div class="search-section">
<input type="text" id="searchTerm" placeholder="Введите запрос для поиска">
<button onclick="searchWiki()">Поиск</button>
<button onclick="refreshResults()">Обновить</button>
</div>
<!-- Контент результатов -->
<div id="result" class="article-info"></div>
</div>
</div>
<!-- Модальное окно -->
<div id="modal" class="modal">
<span class="modal-close" onclick="closeModal()">×</span>
<img id="modalImage" src="" alt="">
</div>
<footer>
©2024 Рувики. Все права защищены.
</footer>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Переменные для хранения предыдущего поиска
let previousSearch = '';
// Функция поиска в Википедии
function searchWiki() {
const searchTerm = document.getElementById('searchTerm').value.trim();
if (!searchTerm) return alert('Пожалуйста, введите запрос для поиска.');
previousSearch = searchTerm; // Сохраняем предыдущий запрос
const apiUrl = `https://ru.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(searchTerm)}&utf8=&format=json&origin=*`;
document.getElementById('result').innerHTML = '<div class="loading">Загрузка...</div>'; // Индикатор загрузки
fetch(apiUrl)
.then(response => {
if (!response.ok) { throw new Error('Network response was not ok'); }
return response.json();
})
.then(data => {
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = '';
if (data.error) {
resultDiv.innerHTML = '<p>Ошибка в запросе API:' + data.error.info + '</p>';
} else if (data.query.search.length === 0) {
resultDiv.innerHTML = '<p>Ничего не найдено.</p>';
} else {
const pageTitle = data.query.search[0].title;
getWikiPage(pageTitle); // Получаем страницу по заголовку
}
})
.catch(error => {
console.error('Ошибка при запросе:', error);
document.getElementById('result').innerHTML = '<p>Ошибка при запросе:' + error.message + '</p>';
});
}
// Функция обновления результатов
function refreshResults() {
searchWiki(); // Повторяем последний поиск
}
// Функция получения страницы из Википедии
function getWikiPage(pageTitle) {
const pageUrl = `https://ru.wikipedia.org/w/api.php?action=parse&page=${encodeURIComponent(pageTitle)}&format=json&origin=*`;
fetch(pageUrl)
.then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); })
.then(data => { const resultDiv = document.getElementById('result'); resultDiv.innerHTML = '';
if (data.error) { resultDiv.innerHTML = '<p>Ошибка при получении данных страницы:' + data.error.info + '</p>'; } else if (data.parse) { let pageContent = data.parse.text['*'];
// Заменяем теги <b>, <strong>, и ссылки на нежно-голубой фон
pageContent = pageContent.replace(/<b>(.*?)<\/b>/g, '<span class="highlight">$1</span>');
pageContent = pageContent.replace(/<strong>(.*?)<\/strong>/g, '<span class="highlight">$1</span>');
pageContent = pageContent.replace(/<a href=["'](.*?)["']>(.*?)<\/a>/g, '<span class="highlight"><a href="$1" style="color:#007aff;text-decoration:none;">$2</a></span>');
// Извлекаем изображения (если есть)
const images = data.parse.images || [];
const imageElements = images.map(image => `<img src="//commons.wikimedia.org/wiki/Special:%20FilePath/${encodeURIComponent(image)}?width=200" alt="${image}" onclick="openModal(this.src)" style="border-radius:12px;margin-right:.5rem;" />`).join('');
const container = document.createElement('div');
// Вставляем контент страницы
container.innerHTML = `<div class='info-block'>${imageElements}<br>${pageContent}</div>`;
// Вставляем содержимое в результат
resultDiv.appendChild(container);
// Добавляем класс для анимации появления
const items = resultDiv.querySelectorAll('.highlight, a');
items.forEach(item => item.classList.add('result-item'));
// Добавляем кнопку для копирования
addCopyButton(resultDiv);
// Добавляем кнопку "Назад"
addBackButton(resultDiv);
// Обновляем содержание бокового меню
updateTOC(container);
}
})
.catch(error => { console.error('Ошибка при запросе страницы:', error); document.getElementById('result').innerHTML = '<p>Ошибка при запросе страницы:' + error.message + '</p>'; });
}
// Функция добавления кнопки копирования
function addCopyButton(resultDiv) {
const copyButton = document.createElement('button');
copyButton.innerText = 'Скопировать статью';
copyButton.style.marginTop = '20px';
copyButton.style.padding = '10px';
copyButton.style.borderRadius = '12px'; // Круглые углы
copyButton.style.backgroundColor = '#007aff'; // Однотонный цвет
copyButton.style.color = 'white';
copyButton.style.border = 'none';
copyButton.style.cursor = 'pointer';
copyButton.onclick = () => {
const articleContent = resultDiv.innerText; // Получаем текст статьи
navigator.clipboard.writeText(articleContent).then(() => {
alert('Статья скопирована в буфер обмена!'); // Уведомление об успешном копировании
}).catch(err => {
console.error('Ошибка при копировании:', err);
});
};
resultDiv.appendChild(copyButton);
}
// Функция добавления кнопки "Назад"
function addBackButton(resultDiv) {
const backButton = document.createElement('button');
backButton.innerText = 'Назад к результатам';
backButton.style.marginTop = '10px';
backButton.style.padding = '10px';
backButton.style.borderRadius = '12px'; // Круглые углы
backButton.style.backgroundColor = '#007aff'; // Однотонный цвет
backButton.style.color = 'white';
backButton.style.border = 'none';
backButton.style.cursor = 'pointer';
backButton.onclick = () => {
document.getElementById('searchTerm').value = previousSearch; // Восстанавливаем предыдущий запрос
searchWiki(); // Повторяем поиск
};
resultDiv.appendChild(backButton);
}
// Функция обновления содержания бокового меню
function updateTOC(container) {
const tocList = document.getElementById('toc');
tocList.innerHTML = ''; // Очищаем текущее содержание
const headings = container.querySelectorAll('h2'); // Находим все заголовки h2
headings.forEach((heading, index) => {
const listItem = document.createElement('li');
listItem.innerHTML = `<a href="#${index}">${heading.innerText}</a>`;
heading.id = index; // Присваиваем уникальный ID каждому заголовку
tocList.appendChild(listItem);
});
}
// Функция переключения видимости контента
function toggleContent(id) {
const contentDiv = document.getElementById(id);
contentDiv.classList.toggle("collapsed");
contentDiv.classList.toggle("expanded");
}
// Функция открытия модального окна с изображением
function openModal(src) {
const modalImage = document.getElementById("modalImage");
modalImage.src = src;
const modal = document.getElementById("modal");
modal.style.display = "block"; // Показываем модальное окно
}
// Функция закрытия модального окна
function closeModal() {
const modal = document.getElementById("modal");
modal.style.display = "none"; // Скрываем модальное окно
}
// Функция для отображения выбранной вкладки
function showTab(tabId) {
const tabsContent = document.querySelectorAll('.tab-content');
tabsContent.forEach(tab => tab.classList.remove('active')); // Скрываем все вкладки
const activeTabContent = document.getElementById(tabId);
activeTabContent.classList.add('active'); // Показываем выбранную вкладку
// Обновляем стиль кнопок вкладок
const tabButtons = document.querySelectorAll('.tab-button');
tabButtons.forEach(button => button.classList.remove('active-tab'));
document.querySelector(`.tab-button[onclick*="${tabId}"]`).classList.add('active-tab'); // Активируем текущую кнопку
}
</script>
</body>
</html>
Теперь у вас должен быть более эстетично улучшенный дизайн с плавными анимациями и улучшенным стилем для вашего приложения в стиле iOS.