blog/_includes/sidebar/article-menu.html

64 lines
1.9 KiB
HTML
Raw Normal View History

2019-09-11 06:19:34 +02:00
<style type="text/css" media="screen">
.post-menu ul {
list-style: none;
padding: 0;
margin: 0;
}
</style>
<div class="post-menu">
<div class="post-menu-title">Contents</div>
<div class="post-menu-content"></div>
</div>
<script>
function generateContent() {
var menu = document.querySelector(".post-menu .post-menu-content");
var headings = document.querySelector(".post-content").querySelectorAll("h2, h3, h4, h5, h6");
2019-09-11 06:19:34 +02:00
// Generate post menu
var menuHTML = '';
for (var i = 0; i < headings.length; i++) {
var h = headings[i];
menuHTML += (
'<li class="h-' + h.tagName.toLowerCase() + '">'
+ '<a href="#h-' + h.getAttribute('id') + '">' + h.textContent + '</a></li>');
}
2019-09-11 06:19:34 +02:00
menu.innerHTML = '<ul>' + menuHTML + '</ul>';
2019-09-11 06:19:34 +02:00
// The header element
var header = document.querySelector('header.site-header');
2019-09-11 06:19:34 +02:00
// Active the menu item
window.addEventListener('scroll', function (event) {
var lastActive = menu.querySelector('.active');
var changed = true;
for (var i = headings.length - 1; i >= 0; i--) {
var h = headings[i];
var headingRect = h.getBoundingClientRect();
var headerRect = header.getBoundingClientRect();
var headerTop = Math.floor(headerRect.top);
var headerHeight = Math.floor(headerRect.height);
var headerHeight = headerTop + headerHeight + 20;
if (headingRect.top <= headerHeight) {
var id = 'h-' + h.getAttribute('id');
var curActive = menu.querySelector('a[href="#' + id + '"]');
if (curActive) {
curActive.classList.add('active');
}
if (lastActive == curActive) {
changed = false;
}
break;
2019-09-11 06:19:34 +02:00
}
}
if (lastActive && changed) {
lastActive.classList.remove('active');
}
event.preventDefault();
});
}
generateContent();
2019-09-11 06:19:34 +02:00
</script>