From 9b5b05463d34f5d8391ae208be72ba2ced75b3f1 Mon Sep 17 00:00:00 2001 From: jeffreytse Date: Mon, 31 Aug 2020 17:21:45 +0800 Subject: feat: auto collapsed menu --- _includes/sidebar/article-menu.html | 47 +++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) (limited to '_includes/sidebar/article-menu.html') diff --git a/_includes/sidebar/article-menu.html b/_includes/sidebar/article-menu.html index 96a4968..215e808 100644 --- a/_includes/sidebar/article-menu.html +++ b/_includes/sidebar/article-menu.html @@ -36,10 +36,49 @@ // The header element var header = document.querySelector('header.site-header'); + function doMenuCollapse(index) { + var items = menuContent.firstChild.children; + var activeItem = items[index]; + var beginItem = activeItem + var endItem = activeItem + var beginIndex = index; + var endIndex = index + 1; + while (beginIndex >= 0 + && !items[beginIndex].classList.contains('h-h2')) { + beginIndex -= 1; + } + while (endIndex < items.length + && !items[endIndex].classList.contains('h-h2')) { + endIndex += 1; + } + for (var i = 0; i < beginIndex; i++) { + item = items[i] + if (!item.classList.contains('h-h2')) { + item.style.display = 'none'; + } + } + for (var i = beginIndex + 1; i < endIndex; i++) { + item = items[i] + // if (!item.classList.contains('h-h2')) { + item.style.display = ''; + // } + } + for (var i = endIndex; i < items.length; i++) { + item = items[i] + if (!item.classList.contains('h-h2')) { + item.style.display = 'none'; + } + } + } + + // Init menu collapsed + doMenuCollapse(-1); + // Active the menu item window.addEventListener('scroll', function (event) { var lastActive = menuContent.querySelector('.active'); var changed = true; + var activeIndex = -1; for (var i = headings.length - 1; i >= 0; i--) { var h = headings[i]; var headingRect = h.getBoundingClientRect(); @@ -53,6 +92,7 @@ var curActive = a.parentNode; if (curActive) { curActive.classList.add('active'); + activeIndex = i; } if (lastActive == curActive) { changed = false; @@ -60,8 +100,11 @@ break; } } - if (lastActive && changed) { - lastActive.classList.remove('active'); + if (changed) { + if (lastActive) { + lastActive.classList.remove('active'); + } + doMenuCollapse(activeIndex); } event.preventDefault(); }); -- cgit v1.2.3