2012-05-22 64 views

回答

0

你可能想看看sticky.js jQuery插件。 它處理這樣的事情很好,如果你不需要它太花哨。

其背後的原理是,以檢查的元件的容器滾動。 得到固定一旦達到一定的滾動水平。

+0

很酷的鏈接。感謝+1。 (幫助你在這裏得到這個地方;)) – mtk

+0

謝謝你,很高興我能幫忙;) – Tharabas

2

當頁面滾動頂部比你要滾動的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

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'); 
    } 
}); 
相關問題