2012-11-01 82 views
-1

我有一個問題,我不能解決這個代碼我用來實現粘滯導航滾動頁面時。問題與jQuery粘滯導航和響應式設計

我希望js不要做任何事情如果瀏覽器窗口寬度低於720px,它可以工作,但只能在第一頁加載。我的意思是,如果我在粘貼導航激活時調整窗口大小,即使將窗口大小調整爲720px,它仍然保持活動狀態。這裏是jQuery的:

//Sticky Navi 
jQuery(function($) { 

// grab the initial top offset of the navigation 
var sticky_navigation_offset_top = $('.main-navigation').offset().top; 
var browserWidth = $(window).width(); 

// our function that decides weather the navigation bar should have "fixed" css position or not. 
var sticky_navigation = function(){ 
    var scroll_top = $(window).scrollTop(); // our current vertical position from the top 

    // if we've 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 && browserWidth > 720) { 
     $('.main-navigation').css({ 'position': 'fixed', 'top':0, 'z-index':999999, 'opacity': 0.9, 'box-shadow': '0px 3px 5px #393939' }) 
    } else { 
     $('.main-navigation').css({ 'position': 'relative', 'opacity': 1, 'box-shadow': 'none' }); 
    } 
}; 

// run our function on load 
sticky_navigation(); 

// and run it again every time you scroll 
$(window).scroll(function() { 
    sticky_navigation(); 
    }); 

}); 

感謝您的幫助

+0

沒有你的HTML和CSS去用它不能做太多。 – Ghlitch

+0

我看不到HTML和CSS如何與問題相關。該腳本的作品我只需要知道如何卸載/禁用jQuery中的功能,當窗口在特定寬度下調整大小時。 – djwd

+0

HTML和CSS總是與任何改變元素的HTML和CSS的JavaScript或jQuery相關。 – Ghlitch

回答

1

就像我在評論說,我不能做沒有你的HTML和CSS,但這裏的一些作品。你有一個奇怪的功能,需要修復。

function sticky_navigation() { 

// grab the initial top offset of the navigation 
var sticky_navigation_offset_top = $('.main-navigation').offset().top; 
var browserWidth = $(window).width(); 
var scroll_top = $(window).scrollTop(); // our current vertical position from the top 

// if we've scrolled more than the navigation, change its position to fixed to stick to top, 
// otherwise change it back to relative 
if ((scroll_top > $('.main-navigation').height()) && (browserWidth > 720)) { 
    $('.main-navigation').css({ 'position': 'fixed', 'top':0, 'z-index':999999, 'opacity': 0.9, 'box-shadow': '0px 3px 5px #393939' }); 
} else { 
    $('.main-navigation').css({ 'position': 'relative', 'opacity': 1, 'box-shadow': 'none' }); 
    } 
}; 

// and run it again every time you scroll 
$(window).scroll(function() { 
    sticky_navigation(); 
}); 

撥弄垃圾HTML:http://jsfiddle.net/cm4t6/

+0

感謝您的幫助,它和以前一樣工作。如果我在頁面滾動時調整窗口大小,它也會影響移動視圖(我不想那樣)。我不是一個jQuery專家,但我想我需要一些東西來檢查腳本加載後窗口是否被調整大小。 – djwd

+0

因爲您只在窗口滾動時調用該函數。如果您想在窗口調整大小時調用該函數,則需要在.resize()觸發器中添加一個鉤子。 – Ghlitch

+0

這裏有一個額外的調整大小觸發器。 http://jsfiddle.net/cm4t6/1/ – Ghlitch