Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make the position of top navbar fixed #982

Merged
merged 14 commits into from
Feb 22, 2020
Merged
39 changes: 39 additions & 0 deletions asset/js/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,52 @@ function flattenModals() {
});
}

function insertCss(cssCode) {
const newNode = document.createElement('style');
newNode.innerHTML = cssCode;
document.getElementsByTagName('head')[0].appendChild(newNode);
}

function setupAnchors() {
const navBarSelector = jQuery('nav, .navbar');
const isFixed = navBarSelector.filter('.navbar-fixed').length !== 0;
const navbarHeight = navBarSelector.height();
const topPadding = 1;
if (isFixed) {
jQuery('.nav-inner').css('padding-top', `calc(${navbarHeight}px + ${2 * topPadding}rem)`);
jQuery('#content-wrapper').css('padding-top', `calc(${navbarHeight}px + ${2 * topPadding}rem)`);
}
jQuery('h1, h2, h3, h4, h5, h6, .header-wrapper').each((index, heading) => {
if (heading.id) {
jQuery(heading).on('mouseenter',
() => jQuery(heading).find('.fa.fa-anchor').css('visibility', 'visible'));
jQuery(heading).on('mouseleave',
() => jQuery(heading).find('.fa.fa-anchor').css('visibility', 'hidden'));
if (isFixed) {
/**
* Fixing the top navbar would break anchor navigation,
* by creating empty spans above the <h> tag we can prevent
* the headings from being covered by the navbar.
*/
const spanId = heading.id;
jQuery(heading).append(
jQuery('<span/>',
{
id: spanId,
class: 'anchor',
},
),
);
jQuery(heading).removeAttr('id'); // to avoid duplicated id problem
const headingHeight = jQuery(heading).height();
le0tan marked this conversation as resolved.
Show resolved Hide resolved
const heightOffset = navbarHeight + headingHeight;
const spanCss = `span#${spanId} { margin-top: calc(-${heightOffset}px - ${topPadding}rem);\n`
+ ' display: block;\n'
+ ` height: calc(${heightOffset}px + ${topPadding}rem);\n`
+ ' visibility: hidden;\n'
+ ' position: relative; }';
insertCss(spanCss);
}
}
});
jQuery('.fa-anchor').each((index, anchor) => {
Expand Down
Loading