I am having a problem with scrolling content smoothly under my fixed position side navigation. When the user scrolls down to the top of my side navigation it becomes fixed. The problem is the content below the fixed navigation jumps to the top of the page instead of scrolling under the fixed nav.
Here is my code: http://jsfiddle.net/grjopa/7GfQ2/1/
In this code example I need the #sidenav-bottom div to scroll smoothly under the fixed position #sidenav div.
What code do I ne开发者_如何学Pythoned to add to accomplish this?
When you apply position:fixed
, it "lifts" the sidenav out of the document flow, causing the content below to jump up to fill the gap. To prevent this, simply insert an empty element that takes up the space (and remove it again, when switching to position:relative
).
See ammended demo: http://jsfiddle.net/7GfQ2/4/.
Note, my demo just shows the basic concept, and I was lazy. You should read all your variables from the DOM and cache them before changing any css properties or adding/removing elements. Currently, it is causing unnecessary page reflows (in a potentially performance-critical section) as it switches between reading from the DOM and modifying the DOM.
This works :
http://jsfiddle.net/7GfQ2/6/
when sidenav is fixed.
$('#sidenav-bottom').css('margin-top',$('#sidenav').height()+20);
when sidenav is relative
$('#sidenav-bottom').css('margin-top','10px');
Using jQuery
There is a very quick way to do what you want using jQuery ScrollToFixed. All credits go to @bigspotteddog in this thread on SO.
精彩评论