I'm building a one-page site with a fixed-positioned navigation bar which scrolls smoothly to the different section elements through anchor links. The default behaviour for scrolling to an element is to align it to the top of the browser window. Instead, I want to align the element to the middle of the screen.
I use this markup for navigation:
<nav class="main-nav">
<a href="#top">Top</a>
<a href="#section-1">Section 1</a>
<a href="#section-2">Section 2</a>
<a href="#section-3">Section 3</a>
<a href="#section-4">Section 4</a>
<a href="#section-5">Section 5</a>
</nav>
I use kswedberg's jQuery Smooth Scroll plugin to smooth the scrolling. I initiate it like this:
$('.main-nav a').smoothScroll({
offset: 0,
speed: 700
});
I want to set the offset to be ((window).height / 2) - (element height / 2)
so that it's vertically centered, but I need help to figure out how to execute it properly.
I need it to:
- Get the height of the window and divide it by two
- Get the height of the element and divide it by two
- Subtract the former from the latter
- If possible, align it to the top as per default if the element is higher than the window
Since there are many anchor links I assume I either need to check the height of the element the anchor link that was clicked links to, or initiate smoothScroll for every anchor link.
Does anybody know how to do this?
question from:
https://stackoverflow.com/questions/18150090/jquery-scroll-element-to-the-middle-of-the-screen-instead-of-to-the-top-with-a 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…