jsfiddle: https://jsfiddle.net/8xo4aghn/
В этой скрипке у меня есть меню, которое подчеркивает элемент, соответствующий текущему разделу, когда страница прокручивается. Последние несколько разделов могут быть короткими (как в этом примере), и они никогда не получают выбор меню. Также можно щелкнуть A-Links, чтобы перейти в раздел, но для последних нескольких, щелчок также не выберет элемент. Возможно ли это, или есть лучшие решения этой проблемы прокрутки? Если бы я сделал это другим путем - показан раздел последнего - тогда нажимать на любые некачественные разделы могли бы также противоречить этому, и были бы аналогичные расхождения.
function updateMenu(){
const menus = document.querySelectorAll('div.sticky a');
const sectionsAll = document.querySelectorAll('div.card');
// Exclude any Sections that don't have an H2
const sections = [...sectionsAll].filter(section => {
const sectionH2 = section.querySelectorAll('h2');
const sectionHeader =
(sectionH2.length ? sectionH2[0] :
null);
if (!sectionHeader) {
return false; //exclude
} else {
return true;
}
});
let currentSection = null;
for (var i = 0; i < sections.length; i++) {
const rect = sections.getBoundingClientRect();
// Find current section; if not last in the list, stop immediately when found
if(rect.top >= 0) {
currentSection = sections;
if (i < sections.length - 1) {
break;
}
}
}
if(currentSection){
// Try to find a matching menu based on the A innerText
menus.forEach(menu => {
const menuInnerText = menu.innerText;
const currentSectionH2 = currentSection.querySelectorAll('h2');
const currentSectionHeader =
(currentSectionH2.length ? currentSectionH2[0] :
null);
if (currentSectionHeader && menuInnerText == currentSectionHeader.innerText) {
// Select menu
menu.classList.add('active');
} else {
// Clear menu
menu.classList.remove('active');
}
});
} else {
// Deselect all menus
menus.forEach(menu => {
menu.classList.remove('active');
});
}
}
window.addEventListener('scroll', updateMenu);
updateMenu(); // initial call
< /code>
Я играл с этим условием, но оно не сработало, < /p>
// Find current section; if not last in the list, stop immediately when found
if(rect.top >= 0) {
currentSection = sections;
if (i < sections.length - 1) {
break;
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... ption-of-l
Выделите пункт меню с прокруткой верхней части секции, за исключением последних видимых разделов ⇐ Javascript
Форум по Javascript
1750432343
Anonymous
jsfiddle: https://jsfiddle.net/8xo4aghn/
В этой скрипке у меня есть меню, которое подчеркивает элемент, соответствующий текущему разделу, когда страница прокручивается. Последние несколько разделов могут быть короткими (как в этом примере), и они никогда не получают выбор меню. Также можно щелкнуть A-Links, чтобы перейти в раздел, но для последних нескольких, щелчок также не выберет элемент. Возможно ли это, или есть лучшие решения этой проблемы прокрутки? Если бы я сделал это другим путем - показан раздел [b] последнего [/b] - тогда нажимать на любые некачественные разделы могли бы также противоречить этому, и были бы аналогичные расхождения.
function updateMenu(){
const menus = document.querySelectorAll('div.sticky a');
const sectionsAll = document.querySelectorAll('div.card');
// Exclude any Sections that don't have an H2
const sections = [...sectionsAll].filter(section => {
const sectionH2 = section.querySelectorAll('h2');
const sectionHeader =
(sectionH2.length ? sectionH2[0] :
null);
if (!sectionHeader) {
return false; //exclude
} else {
return true;
}
});
let currentSection = null;
for (var i = 0; i < sections.length; i++) {
const rect = sections[i].getBoundingClientRect();
// Find current section; if not last in the list, stop immediately when found
if(rect.top >= 0) {
currentSection = sections[i];
if (i < sections.length - 1) {
break;
}
}
}
if(currentSection){
// Try to find a matching menu based on the A innerText
menus.forEach(menu => {
const menuInnerText = menu.innerText;
const currentSectionH2 = currentSection.querySelectorAll('h2');
const currentSectionHeader =
(currentSectionH2.length ? currentSectionH2[0] :
null);
if (currentSectionHeader && menuInnerText == currentSectionHeader.innerText) {
// Select menu
menu.classList.add('active');
} else {
// Clear menu
menu.classList.remove('active');
}
});
} else {
// Deselect all menus
menus.forEach(menu => {
menu.classList.remove('active');
});
}
}
window.addEventListener('scroll', updateMenu);
updateMenu(); // initial call
< /code>
Я играл с этим условием, но оно не сработало, < /p>
// Find current section; if not last in the list, stop immediately when found
if(rect.top >= 0) {
currentSection = sections[i];
if (i < sections.length - 1) {
break;
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79673613/highlight-menu-item-with-top-section-scrolling-into-view-with-the-exception-of-l[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия