Skip to content

Commit 19454c6

Browse files
committed
TOC sidebar: автопрокрутка к активному элементу при скролле
1 parent e055cea commit 19454c6

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

_layouts/post.html

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,13 +197,29 @@ <h3>{{ t.post_discussion }}</h3>
197197
if (h.offsetTop - 100 <= scrollY) current = h.id;
198198
});
199199

200+
var activeLink = null;
200201
tocLinks.forEach(function(link) {
201202
if (link.getAttribute('data-target') === current) {
202203
link.classList.add('active');
204+
activeLink = link;
203205
} else {
204206
link.classList.remove('active');
205207
}
206208
});
209+
210+
if (activeLink) {
211+
var sidebar = document.getElementById('toc-sidebar');
212+
var linkTop = activeLink.offsetTop - sidebar.offsetTop;
213+
var linkBottom = linkTop + activeLink.offsetHeight;
214+
var scrollTop = sidebar.scrollTop;
215+
var viewHeight = sidebar.clientHeight;
216+
217+
if (linkTop < scrollTop + 40) {
218+
sidebar.scrollTo({top: linkTop - 40, behavior: 'smooth'});
219+
} else if (linkBottom > scrollTop + viewHeight - 40) {
220+
sidebar.scrollTo({top: linkBottom - viewHeight + 40, behavior: 'smooth'});
221+
}
222+
}
207223
}
208224

209225
window.addEventListener('scroll', updateToc, {passive: true});

0 commit comments

Comments
 (0)