讓我們做一個基本的積聚:
<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的例子。我們很難用簡單的語言來解釋數學。隨意問,如果有什麼不清楚,應該是! –