http://www.devbridge.com/projects/autocomplete/jquery/元素如何僅在滾動時固定到頁面的頂部?
左邊的邊欄開始打印下來的頁面下,但是當你滾動它移動到頂部,然後保持,而不是消失超出視口的頂部。我見過很多。
http://www.devbridge.com/projects/autocomplete/jquery/元素如何僅在滾動時固定到頁面的頂部?
左邊的邊欄開始打印下來的頁面下,但是當你滾動它移動到頂部,然後保持,而不是消失超出視口的頂部。我見過很多。
當頁面滾動頂部比你要滾動的div的頂部位置時,給該分區的固定位置,使得它遵循用戶失望的頁面。
例子:
在這裏,我硬編碼了榜首的位置,因爲它從來沒有在我的用例的變化。
var $window = $(window), $menu = $("#menu");
$window.bind('scroll', function() {
var pos = +$window.scrollTop();
if (pos > 284) {
$menu.addClass("fixed");
}
else {
$menu.removeClass("fixed");
}
}).trigger("scroll");
,其中固定是將位置設置爲一個固定的班級和頂部爲0
使用jQuery,你增加一個滾動監聽到文檔:
$(document).scroll(function() {
});
內部的功能,您檢查文件的scrollHeight屬性比元素的y位置較大:
if($(document).scrollTop() < $('.sidebar').offset().top) {
// here you change the css attributes position to fixed and top to 0
$('.sidebar').css('position', 'fixed').css('top', 0);
} else {
// change the position of the element to relative (default)
$('.sidebar').css('position', 'relative');
}
這幾乎工作,但因爲你總是檢查固定元件的位置,y位置始終爲0 得到它的工作,你只需要保存默認Y位置。 這是代碼,我也使用:
var initial_y = $('.sidebar').offset().top;
$(document).scroll(function() {
$e = $('.sidebar');
if(initial_y - $(document).scrollTop() <= 0) {
$e.css('position', 'fixed').css('top', 0);
} else {
$e.css('position', 'relative');
}
});
[嘗試從完全一樣的問題,這個答案(http://stackoverflow.com/questions/3704735/jquery-menu-bar-floating-top ) – Codeman