问题
Here is the Problem: Lets say I have something like this:
<div id="leftcontainer">
<div id="top" style="position:fixed"></div>
<div id="below"></div>
</div>
And I would like to have the #below div, below the #top div, but not use margin-top, since the #top div will have different sizes. Also, the #below div can vary in size, and should scroll beneath the #top div.
Does anybody have an idea how to realize that? Greets - Chris
回答1:
This is fairly simple with jQuery if the top div's height is fixed after the page renders.
$(document).ready(function() {
$('#below').css('top', $('#top').outerHeight());
});
That will assign the css top property of the below element equal to the full height of the top element. Other layout factors may cause that to not be the correct value for top, in which case you'll have to determine the correct way to identify the top value, but the principal is the same and in the simple case, this will work without modification.
回答2:
This is the same answer as @hemp, just with the addition of the div constantly updating it's position, by putting the jquery-css inside a function that runs when you resize.
$(document).ready(function() {
function SomeFunction() {
$('#below').css('top', $('#top').outerHeight());
}
window.onresize = SomeFunction;
});
回答3:
I have created this jquery plugin to solve a similar issue I was having where I had a middle container (tabular data) and I wanted the header to fix to the top of the page when the list was scrolled (the list is variable size). One of the issues was, when the header became fixed, the content below it would jump up the page (not good). This plugin compensates for the "fixed" element and allows the content below it to position and scroll as it should.
Here is the link to this jquery plugin that may solve this problem:
https://github.com/bigspotteddog/ScrollToFixed
The description of this plugin is as follows:
This plugin is used to fix elements to the top of the page, if the element would have scrolled out of view, vertically; however, it does allow the element to continue to move left or right with the horizontal scroll.
Given an option marginTop, the element will stop moving vertically upward once the vertical scroll has reached the target position; but, the element will still move horizontally as the page is scrolled left or right. Once the page has been scrolled back down passed the target position, the element will be restored to its original position on the page.
This plugin has been tested in Firefox 3/4, Google Chrome 10/11, Safari 5, and Internet Explorer 8/9.
Usage for your particular case:
<script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery-scrolltofixed-min.js" type="text/javascript"></script>
$(document).ready(function() {
$('#top').scrollToFixed();
});
来源:https://stackoverflow.com/questions/6569681/position-div-below-fixed-div-with-variable-height