Поговорим о...
|
|
AleXStam | Дата: Понедельник, 2025-06-23, 12:37 | Сообщение # 91 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| .tree-search-box { position: relative; display: flex; margin-bottom: 8px; height: 36px; /* Фиксированная высота */ align-items: center; /* Выравнивание по центру */ }
.tree-search-input { flex: 1; height: 36px; /* Фиксированная высота */ padding: 0 30px 0 10px; /* Убрали вертикальные отступы */ border: 1px solid #ddd; border-radius: 4px; font-size: 14px; box-sizing: border-box; /* Учитываем padding в высоте */ }
.tree-search-btn { height: 36px; /* Такая же высота как у поля ввода */ margin-left: 8px; padding: 0 12px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; flex-shrink: 0; /* Не сжимается при скрытии */ transition: opacity 0.2s, width 0.2s, margin 0.2s; }
.tree-search-btn.hidden { opacity: 0; width: 0; margin-left: 0; padding: 0; border: none; overflow: hidden; }
.tree-search-clear { position: absolute; right: 10px; /* Позиция без кнопки */ top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; font-size: 16px; color: #999; transition: right 0.2s; }
.tree-search-box:not(.no-button) .tree-search-clear { right: 90px; /* Позиция с кнопкой */ }
|
|
| |
AleXStam | Дата: Понедельник, 2025-06-23, 12:38 | Сообщение # 92 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| function initSearchMode() { const selectedMode = document.querySelector('input[name="search-mode"]:checked').value; const searchBox = document.querySelector('.tree-search-box'); const searchBtn = document.getElementById('tree-search-btn'); if (selectedMode === 'instant') { // Мгновенный поиск searchBox.classList.add('no-button'); searchBtn.classList.add('hidden'); } else { // Поиск по кнопке searchBox.classList.remove('no-button'); searchBtn.classList.remove('hidden'); } }
|
|
| |
AleXStam | Дата: Понедельник, 2025-06-23, 12:38 | Сообщение # 93 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| <div class="tree-search-panel"> <div class="tree-search-box"> <input type="text" id="tree-search-input" placeholder="Поиск в дереве..." class="tree-search-input"> <button id="tree-search-btn" class="tree-search-btn">Найти</button> <button id="tree-search-clear" class="tree-search-clear" aria-label="Очистить поиск">×</button> </div> <div class="search-modes"> <label><input type="radio" name="search-mode" value="instant"> Мгновенный поиск</label> <label><input type="radio" name="search-mode" value="button" checked> Поиск по кнопке</label> </div> </div>
|
|
| |
AleXStam | Дата: Понедельник, 2025-06-23, 16:14 | Сообщение # 94 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| (function() { // Сохраняем изначальное состояние const initialTreeState = new Map(); let currentSearchMode = 'button';
// Инициализация дерева function initTree() { document.querySelectorAll('.tree-item.has-children').forEach(item => { if (!item.classList.contains('open')) { item.querySelector('.tree-ul').style.display = 'none'; } initialTreeState.set(item, item.classList.contains('open')); });
// Обработчики кликов document.querySelectorAll('.tree-line').forEach(line => { line.addEventListener('click', function() { const item = this.parentElement; if (item.classList.contains('has-children')) { const isOpen = item.classList.contains('open'); item.classList.toggle('open', !isOpen); item.querySelector('.tree-ul').style.display = isOpen ? 'none' : 'block'; } }); }); }
// Очистка всех выделений function clearHighlights() { document.querySelectorAll('.tree-item.highlighted').forEach(item => { item.classList.remove('highlighted'); }); }
// Поиск по дереву function searchTree(query) { const term = query.toLowerCase().trim(); // Очищаем предыдущие выделения clearHighlights(); // Если поиск пустой - сбрасываем к исходному состоянию if (!term) { resetTreeState(); return; }
// Ищем совпадения let foundItems = []; document.querySelectorAll('.tree-item').forEach(item => { const text = item.getAttribute('data-search-text'); if (text.includes(term)) { item.classList.add('highlighted'); foundItems.push(item); // Раскрываем родителей let parent = item.parentElement.closest('.tree-item'); while (parent) { parent.classList.add('open'); parent.querySelector('.tree-ul').style.display = 'block'; parent = parent.parentElement.closest('.tree-item'); } } });
// Если ничего не найдено - сворачиваем всё if (foundItems.length === 0) { document.querySelectorAll('.tree-item.has-children').forEach(item => { item.classList.remove('open'); item.querySelector('.tree-ul').style.display = 'none'; }); } else { // Прокрутка к первому найденному элементу foundItems[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } }
// Сброс к исходному состоянию function resetTreeState() { document.querySelectorAll('.tree-item.has-children').forEach(item => { const shouldBeOpen = initialTreeState.get(item); item.classList.toggle('open', shouldBeOpen); item.querySelector('.tree-ul').style.display = shouldBeOpen ? 'block' : 'none'; }); clearHighlights(); }
// Инициализация при загрузке document.addEventListener('DOMContentLoaded', function() { initTree();
// Обработка URL параметра const urlParams = new URLSearchParams(window.location.search); const urlSearch = urlParams.get('q'); if (urlSearch) { document.getElementById('tree-search-input').value = urlSearch; searchTree(urlSearch); } });
// Экспортируем функции window.searchTree = searchTree; window.resetTreeState = resetTreeState; })();
|
|
| |
AleXStam | Дата: Понедельник, 2025-06-23, 16:15 | Сообщение # 95 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| document.addEventListener('DOMContentLoaded', function() { const searchInput = document.getElementById('tree-search-input'); const searchBtn = document.getElementById('tree-search-btn'); const clearBtn = document.getElementById('tree-search-clear'); const modeRadios = document.querySelectorAll('input[name="search-mode"]'); let searchTimeout; // Обработчик мгновенного поиска function handleInstantSearch() { clearTimeout(searchTimeout); searchTimeout = setTimeout(() => { if (window.searchTree) window.searchTree(this.value); }, 300); } // Инициализация режима поиска function initSearchMode() { const selectedMode = document.querySelector('input[name="search-mode"]:checked').value; const searchBox = document.querySelector('.tree-search-box'); const searchBtn = document.getElementById('tree-search-btn'); // Удаляем все обработчики searchInput.removeEventListener('input', handleInstantSearch); if (selectedMode === 'instant') { // Мгновенный поиск searchInput.addEventListener('input', handleInstantSearch); searchBtn.classList.add('hidden'); searchBox.classList.add('no-button'); } else { // Поиск по кнопке searchBtn.classList.remove('hidden'); searchBox.classList.remove('no-button'); } } // Инициализация initSearchMode(); // Обработчики событий searchBtn.addEventListener('click', function() { if (window.searchTree) window.searchTree(searchInput.value); }); searchInput.addEventListener('keypress', function(e) { if (e.key === 'Enter' && window.searchTree) { window.searchTree(this.value); } }); clearBtn.addEventListener('click', function() { searchInput.value = ''; if (window.resetTreeState) window.resetTreeState(); }); // Переключение режимов modeRadios.forEach(radio => { radio.addEventListener('change', initSearchMode); }); });
|
|
| |
AleXStam | Дата: Понедельник, 2025-06-23, 16:18 | Сообщение # 96 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| document.addEventListener('DOMContentLoaded', function() { const searchInput = document.getElementById('tree-search-input'); const searchBtn = document.getElementById('tree-search-btn'); const clearBtn = document.getElementById('tree-search-clear'); const modeRadios = document.querySelectorAll('input[name="search-mode"]'); let searchTimeout; // Обработчик мгновенного поиска function handleInstantSearch() { clearTimeout(searchTimeout); searchTimeout = setTimeout(() => { if (window.searchTree) window.searchTree(this.value); }, 300); } // Инициализация режима поиска function initSearchMode() { const selectedMode = document.querySelector('input[name="search-mode"]:checked').value; const searchBox = document.querySelector('.tree-search-box'); const searchBtn = document.getElementById('tree-search-btn'); // Удаляем все обработчики searchInput.removeEventListener('input', handleInstantSearch); if (selectedMode === 'instant') { // Мгновенный поиск searchInput.addEventListener('input', handleInstantSearch); searchBtn.classList.add('hidden'); searchBox.classList.add('no-button'); } else { // Поиск по кнопке searchBtn.classList.remove('hidden'); searchBox.classList.remove('no-button'); } } // Инициализация initSearchMode(); // Обработчики событий searchBtn.addEventListener('click', function() { if (window.searchTree) window.searchTree(searchInput.value); }); searchInput.addEventListener('keypress', function(e) { if (e.key === 'Enter' && window.searchTree) { window.searchTree(this.value); } }); clearBtn.addEventListener('click', function() { searchInput.value = ''; if (window.resetTreeState) window.resetTreeState(); }); // Переключение режимов modeRadios.forEach(radio => { radio.addEventListener('change', initSearchMode); }); });
|
|
| |
Гость | Дата: Вторник, 2025-06-24, 08:20 | Сообщение # 97 |
Группа: Гости
| {{% details title="Интрузивные образования" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Пикрит | | | Пикрит щелочной | | | Брекчия щелочных пикритов | | | Порфирит пикритовый | | | Пироксенит | | | Базальт | | | Долерит | | | Долериты, долеритобазальты | | | Микродолерит | | | Долериты тонко-микрокристаллически | | | Долерит тонкокристаллический | | | Долериты тонко-мелкокристаллически | | | Долерит мелкокристаллический | | | Долериты мелко-среднекристаллические | | | Долерит среднекристаллический | | | Долериты средне-крупнокристаллические | | | Долерит крупнокристаллический | | | Гранит | | | Пегматит | | | Габбро |
{{% /details %}}
{{% details title="Вторичные изменения" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Глина карбонатная с щебнем и дресвой | | | Глина с щебнем и дресвой | | | Глина карбонатная | | | Глина бокситовая | | | Глина алевритистая | | | Глина песчаная | | | Глина с обломками терригенных пород | | | Глина с обломками карбонатных пород | | | Глина-аргиллит-щебнистое отложение | | | Глина с обломками долеритов | | | Глина с обломками пород | | | Кора выветривания по кимберлитам | | | Кора выветривания по долеритам | | | Кора выветривания по карбонатным породам | | | Карстовое образование в известняках | | | Выветрелые карбонатные породы | | | Породы зоны дробления | | | Порода окремненная | | | Порода пиритизированная |
{{% /details %}}
{{% details title="Неклассифицируемые образования" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Бетон | | | Вода | | | Лед | | | Техногенные отложения |
{{% /details %}}
{{< tabs items="Осадочные, Вулканогенно-осадочные, Вулканогенные, Метаморфические, Тектонические" >}}
{{< tab >}} {{% details title="Нелитифицированные обломочные и глинистые осадочные породы" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Почвенно-растительный слой | | | Торф | | | Суглинок | | | Суглинок с
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 08:25 | Сообщение # 98 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| {{% details title="Поиск пород" closed="true" %}} <div class="search-container"> <input type="text" id="rockSearch" onkeyup="searchRocks()" placeholder="Поиск пород..."> </div>
<style> .search-container { margin: 20px 0; } #rockSearch { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; } </style>
<script> function searchRocks() { const input = document.getElementById('rockSearch'); const filter = input.value.toUpperCase(); const details = document.querySelectorAll('details[title*="Интрузивные"], details[title*="Вторичные"], details[title*="Неклассифицируемые"], details[title*="Нелитифицированные"]'); details.forEach(detail => { const tables = detail.querySelectorAll('table'); let hasVisibleRows = false; tables.forEach(table => { const rows = table.querySelectorAll('tr'); rows.forEach(row => { const cell = row.querySelector('td:nth-child(2)'); if (cell) { const txtValue = cell.textContent || cell.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { row.style.display = ""; hasVisibleRows = true; } else { row.style.display = "none"; } } }); }); // Показываем/скрываем всю секцию в зависимости от наличия результатов if (hasVisibleRows) { detail.style.display = ""; detail.open = true; // Разворачиваем секцию с результатами } else { detail.style.display = "none"; } }); } </script> {{% /details %}}
{{% details title="Интрузивные образования" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Пикрит | | | Пикрит щелочной | | | Брекчия щелочных пикритов | | | Порфирит пикритовый | | | Пироксенит | | | Базальт | | | Долерит | | | Долериты, долеритобазальты | | | Микродолерит | | | Долериты тонко-микрокристаллически | | | Долерит тонкокристаллический | | | Долериты тонко-мелкокристаллически | | | Долерит мелкокристаллический | | | Долериты мелко-среднекристаллические | | | Долерит среднекристаллический | | | Долериты средне-крупнокристаллические | | | Долерит крупнокристаллический | | | Гранит | | | Пегматит | | | Габбро |
{{% /details %}}
{{% details title="Вторичные изменения" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Глина карбонатная с щебнем и дресвой | | | Глина с щебнем и дресвой | | | Глина карбонатная | | | Глина бокситовая | | | Глина алевритистая | | | Глина песчаная | | | Глина с обломками терригенных пород | | | Глина с обломками карбонатных пород | | | Глина-аргиллит-щебнистое отложение | | | Глина с обломками долеритов | | | Глина с обломками пород | | | Кора выветривания по кимберлитам | | | Кора выветривания по долеритам | | | Кора выветривания по карбонатным породам | | | Карстовое образование в известняках | | | Выветрелые карбонатные породы | | | Породы зоны дробления | | | Порода окремненная | | | Порода пиритизированная |
{{% /details %}}
{{% details title="Неклассифицируемые образования" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Бетон | | | Вода | | | Лед | | | Техногенные отложения |
{{% /details %}}
{{< tabs items="Осадочные, Вулканогенно-осадочные, Вулканогенные, Метаморфические, Тектонические" >}}
{{< tab >}} {{% details title="Нелитифицированные обломочные и глинистые осадочные породы" closed="true" %}}
|Крап | Порода | |:-------------------:|------------| | | Почвенно-растительный слой | | | Торф | | | Суглинок | | | Суглинок с обломками пород | {{% /details %}}
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 08:38 | Сообщение # 99 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| {{% details title="Поиск пород" closed="true" %}} <div class="search-container"> <input type="text" id="rockSearch" placeholder="Поиск пород..." class="search-input"> </div>
<style> .search-container { margin: 20px 0; padding: 10px; background: #f5f5f5; border-radius: 5px; } .search-input { width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 16px; } </style>
<script> document.addEventListener('DOMContentLoaded', function() { const searchInput = document.getElementById('rockSearch'); searchInput.addEventListener('input', function() { const searchTerm = this.value.trim().toLowerCase(); const allDetails = document.querySelectorAll('details[title]:not([title="Поиск пород"])'); let anyResultsFound = false; allDetails.forEach(detail => { const tables = detail.querySelectorAll('table'); let sectionHasResults = false; tables.forEach(table => { const rows = table.querySelectorAll('tr:not(:first-child)'); let tableHasResults = false; rows.forEach(row => { const rockNameCell = row.querySelector('td:nth-child(2)'); if (rockNameCell) { const rockName = rockNameCell.textContent.toLowerCase(); if (searchTerm === '' || rockName.includes(searchTerm)) { row.style.display = ''; tableHasResults = true; sectionHasResults = true; anyResultsFound = true; } else { row.style.display = 'none'; } } }); // Показывать/скрывать таблицу в зависимости от результатов table.style.display = tableHasResults ? '' : 'none'; }); // Управление видимостью всей секции if (sectionHasResults || searchTerm === '') { detail.style.display = ''; detail.open = true; } else { detail.style.display = 'none'; } }); // Если нет результатов, показать сообщение const noResultsMsg = document.getElementById('noResults'); if (searchTerm !== '' && !anyResultsFound) { if (!noResultsMsg) { const msg = document.createElement('div'); msg.id = 'noResults'; msg.textContent = 'Ничего не найдено'; msg.style.padding = '10px'; msg.style.color = '#666'; searchInput.insertAdjacentElement('afterend', msg); } } else if (noResultsMsg) { noResultsMsg.remove(); } }); }); </script> {{% /details %}}
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 08:43 | Сообщение # 100 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| {{% details title="Поиск в списке пород" closed="true" %}} <script> function setupRockSearch() { // Создаем элементы интерфейса const searchContainer = document.createElement('div'); searchContainer.className = 'rock-search-container'; const searchInput = document.createElement('input'); searchInput.type = 'text'; searchInput.placeholder = 'Введите название породы...'; searchInput.className = 'rock-search-input'; const noResultsMsg = document.createElement('div'); noResultsMsg.className = 'rock-no-results'; noResultsMsg.textContent = 'Ничего не найдено'; noResultsMsg.style.display = 'none'; searchContainer.appendChild(searchInput); searchContainer.appendChild(noResultsMsg); // Вставляем перед первым списком пород const firstRockSection = document.querySelector('details[title^="Интрузивные"]'); if (firstRockSection) { firstRockSection.parentNode.insertBefore(searchContainer, firstRockSection); } // Функция поиска searchInput.addEventListener('input', function() { const searchTerm = this.value.trim().toLowerCase(); const rockSections = document.querySelectorAll('details[title^="Интрузивные"], details[title^="Вторичные"], details[title^="Неклассифицируемые"], details[title^="Нелитифицированные"]'); let anyResultsFound = false; rockSections.forEach(section => { const rows = section.querySelectorAll('table tr'); let sectionHasResults = false; // Пропускаем заголовок таблицы for (let i = 1; i < rows.length; i++) { const row = rows[i]; const rockNameCell = row.querySelector('td:nth-child(2)'); if (rockNameCell) { const rockName = rockNameCell.textContent.toLowerCase(); if (searchTerm === '' || rockName.includes(searchTerm)) { row.style.display = ''; sectionHasResults = true; anyResultsFound = true; } else { row.style.display = 'none'; } } } // Управление видимостью секции if (sectionHasResults || searchTerm === '') { section.style.display = ''; section.open = true; } else { section.style.display = 'none'; } }); // Показываем сообщение, если нет результатов noResultsMsg.style.display = (searchTerm !== '' && !anyResultsFound) ? 'block' : 'none'; }); }
// Запускаем после загрузки страницы document.addEventListener('DOMContentLoaded', setupRockSearch); </script>
<style> .rock-search-container { margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 5px; border: 1px solid #dee2e6; }
.rock-search-input { width: 100%; padding: 8px 12px; border: 1px solid #ced4da; border-radius: 4px; font-size: 16px; }
.rock-no-results { padding: 10px; color: #6c757d; text-align: center; font-style: italic; margin-top: 10px; } </style> {{% /details %}}
Основные особенности этого решения:
1. **Изолированный поиск**, который работает только с вашими списками пород и не конфликтует с другими элементами страницы.
2. **Автоматическое разворачивание** секций, где найдены результаты.
3. **Чистый JavaScript** без зависимостей от других библиотек.
4. **Улучшенный интерфейс**: - Поле поиска появляется перед списками пород - Сообщение "Ничего не найдено" при отсутствии результатов - Стили, которые не конфликтуют с основной темой
5. **Поиск только по названиям пород** (второй столбец таблиц).
Если поиск все равно не работает, пожалуйста, проверьте: 1. Нет ли ошибок в консоли браузера (F12 → Console) 2. Правильно ли загружаются скрипты на вашей странице 3. Соответствует ли структура HTML ожидаемой (должны быть таблицы внутри details)
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 08:45 | Сообщение # 101 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| <div class="rock-search-container"> <input type="text" class="rock-search-input" placeholder="Поиск пород..." id="rockSearchInput"> <div class="rock-no-results" style="display:none">Ничего не найдено</div> </div>
<script> document.addEventListener('DOMContentLoaded', function() { const searchInput = document.getElementById('rockSearchInput'); const noResultsMsg = document.querySelector('.rock-no-results'); if (!searchInput) return; searchInput.addEventListener('input', function() { const searchTerm = this.value.trim().toLowerCase(); const rockSections = document.querySelectorAll('details[title*="Интрузивные"], details[title*="Вторичные"], details[title*="Неклассифицируемые"], details[title*="Нелитифицированные"]'); let anyResultsFound = false; rockSections.forEach(section => { const tables = section.querySelectorAll('table'); let sectionHasResults = false; tables.forEach(table => { const rows = table.querySelectorAll('tr'); let tableHasResults = false; rows.forEach((row, index) => { // Пропускаем заголовок таблицы if (index === 0) return; const rockNameCell = row.querySelector('td:nth-child(2)'); if (rockNameCell) { const rockName = rockNameCell.textContent.toLowerCase(); if (searchTerm === '' || rockName.includes(searchTerm)) { row.style.display = ''; tableHasResults = true; sectionHasResults = true; anyResultsFound = true; } else { row.style.display = 'none'; } } }); // Показывать/скрывать таблицу table.style.display = tableHasResults || searchTerm === '' ? '' : 'none'; }); // Управление секцией if (sectionHasResults || searchTerm === '') { section.style.display = ''; section.open = true; } else { section.style.display = 'none'; } }); // Сообщение о результатах noResultsMsg.style.display = (searchTerm !== '' && !anyResultsFound) ? 'block' : 'none'; }); }); </script>
<style> .rock-search-container { margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 5px; border: 1px solid #dee2e6; }
.rock-search-input { width: 100%; padding: 10px 15px; border: 1px solid #ced4da; border-radius: 4px; font-size: 16px; box-sizing: border-box; }
.rock-no-results { padding: 10px; color: #6c757d; text-align: center; font-style: italic; margin-top: 10px; } </style>
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 08:48 | Сообщение # 102 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| <!-- Добавьте этот код ПЕРЕД всеми секциями с породами --> <div class="custom-rock-search"> <input type="text" placeholder="Начните вводить название породы..." class="rock-search-field"> <div class="search-hint">Найдено: <span class="matches-count">0</span></div> </div>
<style> .custom-rock-search { margin: 20px 0; padding: 15px; background: #f5f7fa; border-radius: 8px; border: 1px solid #e1e4e8; }
.rock-search-field { width: 100%; padding: 10px 15px; border: 1px solid #d1d5da; border-radius: 6px; font-size: 16px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); }
.search-hint { margin-top: 8px; font-size: 14px; color: #586069; display: none; }
.highlight-match { background-color: #fff8c5; font-weight: bold; } </style>
<script> document.addEventListener('DOMContentLoaded', function() { const searchField = document.querySelector('.rock-search-field'); const searchHint = document.querySelector('.search-hint'); const matchesCount = document.querySelector('.matches-count'); if (!searchField) return;
// Все секции, где нужно искать const rockSections = [ ...document.querySelectorAll('details[title*="Интрузивные"]'), ...document.querySelectorAll('details[title*="Вторичные"]'), ...document.querySelectorAll('details[title*="Неклассифицируемые"]'), ...document.querySelectorAll('details[title*="Нелитифицированные"]') ];
searchField.addEventListener('input', function() { const searchTerm = this.value.trim().toLowerCase(); let totalMatches = 0;
// Сбрасываем предыдущие результаты document.querySelectorAll('.highlight-match').forEach(el => { el.classList.remove('highlight-match'); });
if (searchTerm === '') { searchHint.style.display = 'none'; rockSections.forEach(section => { section.style.display = ''; }); return; }
rockSections.forEach(section => { const rows = section.querySelectorAll('table tr:not(:first-child)'); let sectionHasMatches = false;
rows.forEach(row => { const nameCell = row.querySelector('td:nth-child(2)'); if (nameCell) { const text = nameCell.textContent.toLowerCase(); if (text.includes(searchTerm)) { nameCell.classList.add('highlight-match'); sectionHasMatches = true; totalMatches++; } } });
// Управление отображением секции if (sectionHasMatches) { section.style.display = ''; section.open = true; // Раскрываем секцию } else { section.style.display = 'none'; } });
// Показываем количество найденных результатов if (totalMatches > 0) { matchesCount.textContent = totalMatches; searchHint.style.display = 'block'; } else { searchHint.style.display = 'none'; } }); }); </script>
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 08:51 | Сообщение # 103 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| <!-- Добавьте этот код ПЕРЕД всеми секциями с породами --> <div id="rockSearchContainer" style="margin: 20px 0; padding: 15px; background: #f5f5f5; border-radius: 5px;"> <input type="text" id="rockSearchInput" placeholder="Введите название породы..." style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 16px;"> <div id="searchResultsInfo" style="display: none; margin-top: 10px; color: #666;"> Найдено совпадений: <span id="matchesCount">0</span> </div> </div>
<script> // Ждём полной загрузки страницы window.addEventListener('load', function() { // Получаем элементы const searchInput = document.getElementById('rockSearchInput'); const resultsInfo = document.getElementById('searchResultsInfo'); const matchesCount = document.getElementById('matchesCount'); // Если элементы не найдены, прекращаем работу if (!searchInput || !resultsInfo || !matchesCount) return; // Все секции с породами const rockSections = document.querySelectorAll( 'details[title*="Интрузивные"], ' + 'details[title*="Вторичные"], ' + 'details[title*="Неклассифицируемые"], ' + 'details[title*="Нелитифицированные"]' ); // Обработчик ввода searchInput.addEventListener('input', function() { const searchTerm = this.value.trim().toLowerCase(); let foundCount = 0; // Сбрасываем предыдущие результаты document.querySelectorAll('.search-highlight').forEach(el => { el.classList.remove('search-highlight'); }); if (searchTerm === '') { resultsInfo.style.display = 'none'; rockSections.forEach(section => { section.style.display = 'block'; }); return; } // Ищем в каждой секции rockSections.forEach(section => { const rows = section.querySelectorAll('tr'); let sectionHasMatches = false; rows.forEach(row => { const cells = row.querySelectorAll('td'); if (cells.length >= 2) { // Проверяем, что есть второй столбец const rockName = cells[1].textContent.toLowerCase(); if (rockName.includes(searchTerm)) { cells[1].classList.add('search-highlight'); foundCount++; sectionHasMatches = true; } } }); // Управляем отображением секции if (sectionHasMatches) { section.style.display = 'block'; section.open = true; // Раскрываем секцию } else { section.style.display = 'none'; } }); // Показываем информацию о результатах matchesCount.textContent = foundCount; resultsInfo.style.display = foundCount > 0 ? 'block' : 'none'; }); });
// Добавляем стили для подсветки const style = document.createElement('style'); style.textContent = ` .search-highlight { background-color: #ffeb3b; font-weight: bold; padding: 2px 4px; border-radius: 3px; } `; document.head.appendChild(style); </script>
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 10:05 | Сообщение # 104 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| <!-- Вставьте этот код ПЕРЕД всеми секциями с породами --> <div id="rockSearchSystem" style="margin: 20px 0; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e1e4e8;"> <input type="text" id="rockSearchField" placeholder="Введите название породы..." style="width: 100%; padding: 12px 15px; border: 1px solid #d1d5da; border-radius: 6px; font-size: 16px;"> <div id="searchStatus" style="margin-top: 10px; color: #586069; font-size: 14px;">Готов к поиску</div> </div>
<script> // Функция для отладки - выводит информацию о структуре страницы function debugPageStructure() { console.group('Debugging Rock Search'); // Проверяем наличие поискового поля const searchField = document.getElementById('rockSearchField'); console.log('Поисковое поле:', searchField ? 'Найдено' : 'Не найдено'); // Проверяем наличие секций с породами const sections = document.querySelectorAll('details[title*="Интрузивные"], details[title*="Вторичные"], details[title*="Неклассифицируемые"], details[title*="Нелитифицированные"]'); console.log('Найдено секций с породами:', sections.length); if (sections.length > 0) { // Проверяем структуру первой секции const firstSection = sections[0]; console.log('Первая секция:', firstSection); const tables = firstSection.querySelectorAll('table'); console.log('Таблиц в секции:', tables.length); if (tables.length > 0) { const rows = tables[0].querySelectorAll('tr'); console.log('Строк в таблице:', rows.length); if (rows.length > 1) { const cells = rows[1].querySelectorAll('td'); console.log('Ячеек в строке:', cells.length); } } } console.groupEnd(); }
// Основная функция поиска function initializeRockSearch() { const searchField = document.getElementById('rockSearchField'); const searchStatus = document.getElementById('searchStatus'); if (!searchField || !searchStatus) { console.error('Не найдены необходимые элементы для поиска'); return; } // Динамически добавляем стили для подсветки const style = document.createElement('style'); style.textContent = ` .rock-search-match { background-color: #fff3bf; font-weight: bold; border-radius: 3px; padding: 0 2px; } .hidden-section { display: none !important; } `; document.head.appendChild(style); // Обработчик поиска searchField.addEventListener('input', function() { const searchTerm = this.value.trim().toLowerCase(); let foundCount = 0; // Сбрасываем предыдущие результаты document.querySelectorAll('.rock-search-match').forEach(el => { el.classList.remove('rock-search-match'); }); const allSections = document.querySelectorAll( 'details[title*="Интрузивные"], ' + 'details[title*="Вторичные"], ' + 'details[title*="Неклассифицируемые"], ' + 'details[title*="Нелитифицированные"]' ); if (allSections.length === 0) { searchStatus.textContent = 'Не найдено секций с породами'; return; } allSections.forEach(section => { const tables = section.querySelectorAll('table'); let sectionHasMatches = false; tables.forEach(table => { const rows = table.querySelectorAll('tr'); rows.forEach((row, index) => { // Пропускаем заголовок таблицы if (index === 0) return; const cells = row.querySelectorAll('td'); if (cells.length >= 2) { const rockName = cells[1].textContent.toLowerCase(); if (searchTerm === '' || rockName.includes(searchTerm)) { if (searchTerm !== '') { cells[1].classList.add('rock-search-match'); } foundCount++; sectionHasMatches = true; } } }); }); // Управляем отображением секции if (searchTerm === '' || sectionHasMatches) { section.style.display = ''; section.open = true; section.classList.remove('hidden-section'); } else { section.style.display = 'none'; section.classList.add('hidden-section'); } }); // Обновляем статус if (searchTerm === '') { searchStatus.textContent = 'Введите название породы для поиска'; } else if (foundCount > 0) { searchStatus.textContent = `Найдено совпадений: ${foundCount}`; } else { searchStatus.textContent = 'Ничего не найдено'; } }); // Запускаем отладку debugPageStructure(); }
// Запускаем после полной загрузки страницы window.addEventListener('load', function() { // Даём небольшую задержку на случай динамической загрузки контента setTimeout(initializeRockSearch, 500); }); </script>
|
|
| |
AleXStam | Дата: Вторник, 2025-06-24, 10:12 | Сообщение # 105 |
Генералиссимус
Группа: Администраторы
Сообщений: 200
Награды: 1
Репутация: 10003
Статус: Оффлайн
| <!-- Вставьте этот код ПЕРЕД всеми секциями с породами --> <div id="rockSearchSystem" style="margin: 20px 0; padding: 20px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e1e4e8;"> <div style="display: flex; gap: 10px;"> <input type="text" id="rockSearchField" placeholder="Введите название породы..." style="flex: 1; padding: 12px 15px; border: 1px solid #d1d5da; border-radius: 6px; font-size: 16px;"> <button id="rockSearchButton" style="padding: 12px 20px; background: #2188ff; color: white; border: none; border-radius: 6px; cursor: pointer;"> Поиск </button> </div> <div id="searchStatus" style="margin-top: 10px; color: #586069; font-size: 14px;">Готов к поиску</div> </div>
<script> // Функция для поиска пород function searchRocks() { const searchField = document.getElementById('rockSearchField'); const searchStatus = document.getElementById('searchStatus'); if (!searchField || !searchStatus) { console.error('Элементы поиска не найдены'); return; } const searchTerm = searchField.value.trim().toLowerCase(); let foundCount = 0; // Сбрасываем предыдущие результаты document.querySelectorAll('.rock-search-match').forEach(el => { el.classList.remove('rock-search-match'); }); // Находим ВСЕ секции details на странице (универсальный вариант) const allSections = document.querySelectorAll('details'); if (allSections.length === 0) { searchStatus.textContent = 'Не найдено ни одной секции на странице'; return; } allSections.forEach(section => { const tables = section.querySelectorAll('table'); let sectionHasMatches = false; tables.forEach(table => { const rows = table.querySelectorAll('tr'); rows.forEach((row, index) => { // Пропускаем заголовок таблицы if (index === 0) return; const cells = row.querySelectorAll('td'); // Ищем во всех ячейках строки (на случай если структура отличается) cells.forEach(cell => { const text = cell.textContent.toLowerCase(); if (searchTerm !== '' && text.includes(searchTerm)) { cell.classList.add('rock-search-match'); foundCount++; sectionHasMatches = true; } }); }); }); // Управление отображением секции if (searchTerm === '' || sectionHasMatches) { section.style.display = ''; section.open = true; } else { section.style.display = 'none'; } }); // Обновляем статус if (searchTerm === '') { searchStatus.textContent = 'Введите название породы для поиска'; } else if (foundCount > 0) { searchStatus.textContent = `Найдено совпадений: ${foundCount}`; } else { searchStatus.textContent = 'Ничего не найдено'; } }
// Инициализация поиска function initializeRockSearch() { // Добавляем стили для подсветки const style = document.createElement('style'); style.textContent = ` .rock-search-match { background-color: #fff3bf; font-weight: bold; border-radius: 3px; padding: 0 2px; } .hidden-section { display: none !important; } `; document.head.appendChild(style); // Обработчики событий const searchField = document.getElementById('rockSearchField'); const searchButton = document.getElementById('rockSearchButton'); if (searchField && searchButton) { // Поиск при нажатии кнопки searchButton.addEventListener('click', searchRocks); // Поиск при нажатии Enter в поле ввода searchField.addEventListener('keypress', function(e) { if (e.key === 'Enter') { searchRocks(); } }); // Быстрый поиск при вводе (с задержкой 300мс) let typingTimer; searchField.addEventListener('input', function() { clearTimeout(typingTimer); typingTimer = setTimeout(searchRocks, 300); }); } }
// Запускаем после загрузки страницы window.addEventListener('DOMContentLoaded', initializeRockSearch); </script>
|
|
| |