让我们做一个基本的积聚:
<div id="content">Content to be scrolled as Wrapper </div>
<div id="mydiv" class="fixed"> Div that should be fixed </div>
<div id="end"> Everything after the fixed div </div>
我们迅速在底部使用类.fixed
,这样我们就可以使用.addClass('fixed')
和.removeClass('fixed')
切换解决您的div一些CSS属性。
.fixed {
position: fixed;
bottom: 0;
}
所以有此.scrollTop
功能,可以让我们从顶部向底部滚动一定量的像素。这已经正是你所需要的。窍门是知道固定元素顶部有多少像素应该开始滚动内容。
让我们做一些jQuery来了解一下:
// Create function to add/remove Class if .scrollTop
$.fn.followTo = function (pos) {
var $this = this,
$window = $(window);
$window.scroll(function (e) {
if ($window.scrollTop() < pos) {
$this.addClass('fixed');
} else {
$this.removeClass('fixed');
}
});
};
var $height_content = $('#content').outerHeight(); //get height of content
var $height_div = $('#mydiv').outerHeight(); //get height of fixed div
var $height_viewport = $(window).height(); //get height of viewport
var $fixed_till = ($height_content + $height_div - $height_viewport);
// Use function created above like so:
// $('selector').followTo(/* height from top in px */);
$('#mydiv').followTo($fixed_till);
检查DEMO ON JSFIDDLE
创建** **小提琴,你期待什么,并张贴一些'html'呢! –
试试看这里:https://css-tricks.com/scroll-fix-content/ –
我编辑了我的答案不少次,但这次应该没有错误和一个工作jsfiddle的例子。我们很难用简单的语言来解释数学。随意问,如果有什么不清楚,应该是! –