我發現了一個用於在網站上使用的粘性導航的jQuery腳本。粘性導航腳本在瀏覽器調整大小後無法正常工作
$(function() {
// grab the initial top offset of the navigation
var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;
// the function that decides weather the navigation bar should have "fixed" css position or not
var sticky_navigation = function(){
var scroll_top = $(window).scrollTop(); // the current vertical position from the top
// if user scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
if (scroll_top > sticky_navigation_offset_top) {
$('#sticky_navigation').css({ 'position': 'fixed', 'top':-23, 'left':0 });
} else {
$('#sticky_navigation').css({ 'position': 'relative', 'top':-30 });
}
};
// run the function on load
sticky_navigation();
// and run it again every time you scroll
$(window).scroll(function() {
sticky_navigation();
});
});
它只工作乾淨,如果我不加載網站後調整瀏覽器的大小。如果我做了調整大小,那麼腳本不知道新的大小,滾動時導航欄跳轉到不同的位置。我試圖添加一個
$(window).resize(function() {
sticky_navigation();
});
但它沒有做任何事情。
應該不難告訴腳本在調整大小後檢查頂部偏移量。 但我不是程序員,所以如果可以的話,請給我一些代碼示例的建議,而不僅僅是理論上的推理。
希望有人能幫助我。
編輯: 這裏的的jsfiddle例如: http://jsfiddle.net/p9Lvbz68/8/
嘗試定義sticky_navigation函數內部sticky_navigation_offset_top不在外面 –
我想它就像你說的,它似乎工作,但導航現在堅持到頂部,不扯去。 – sveto
夥計們,我不明白你爲什麼要改變腳本的行爲不同。僅僅添加一個關於window resize/sizechange的請求是不是更有意義,所以腳本每次用戶調整瀏覽器大小時都會更新這些值? :) – sveto