Side nav automatically scrolls the selected item into view

This commit is contained in:
pgonzal 2018-09-10 17:40:20 -07:00
Родитель a0a78c29e3
Коммит 989da2236e
2 изменённых файлов: 24 добавлений и 1 удалений

Просмотреть файл

@ -11,7 +11,8 @@
{% for subitem in item.subitems %}
{% assign temp = subitem.url | append: '/' %}
{% if page.url == subitem.url or page.url == temp %}
<li class="docsite-side-nav-selection"><a href="{{ subitem.url }}">{{ subitem.title }}</a></li>
<li id="docsite-side-nav-selection" class="docsite-side-nav-selection">
<a href="{{ subitem.url }}">{{ subitem.title }}</a></li>
{% else %}
<li><a href="{{ subitem.url }}">{{ subitem.title }}</a></li>
{% endif %}

Просмотреть файл

@ -51,7 +51,29 @@ function updateScriptedSidebar() {
}
}
function scrollToSelectedNavItem() {
// If the current page is highlighted in the side nav,
// then scroll that item into view
let navSelection = document.getElementById('docsite-side-nav-selection');
if (navSelection && navSelection.scrollIntoView) {
// Is it in already in view?
let bounding = navSelection.getBoundingClientRect();
let isInView =
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth);
if (!isInView) {
navSelection.scrollIntoView( { block: "center" });
}
}
}
window.addEventListener("scroll", updateScriptedSidebar);
window.addEventListener("resize", updateScriptedSidebar);
window.addEventListener("load", updateScriptedSidebar);
window.addEventListener("load", scrollToSelectedNavItem);
</script>