仅当大于960px时粘性导航

时间:2013-03-12 21:29:40

标签: jquery navigation sticky

我对jquery有疑问。我只是在窗口大小超过960px时尝试应用粘性导航。所以我需要检查是否有窗口大小调整或滚动事件......我无法弄明白......

有人可以帮我修理那些东西吗?

这是我试图改编的代码

$(function() {

    var sticky_navigation_offset_top = $('#nav').offset().top;

    var sticky_navigation = function(){
        var scroll_top = $(window).scrollTop(); // our current vertical position from the top

        if (scroll_top > sticky_navigation_offset_top) { 
            $('#nav').css({ 'position': 'fixed', 'top':0, 'left':0 });


        } else {
            $('#nav').css({ 'position': 'relative' }); 
        }   
    };

    sticky_navigation();

    $(window).resize(function() {
  if ($(window).width() > 960) {
        $(window).scroll(function() {
         sticky_navigation();
    });
  }
});
});

2 个答案:

答案 0 :(得分:0)

LIVE DEMO

function stickNav() { 
    var setPosition = $(window).width() > 960 ? 'fixed' : 'relative';
    $('#nav').css({position:setPosition, left:0, top:0});
}


$(function() {
    stickNav();  // Do it on DOM ready
});

$(window).resize(function() {
    stickNav();  // Do in on Resize
});

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

答案 1 :(得分:0)

roXon没有考虑导航偏移,并且必须在调整大小和滚动时进行计算。

这是我的解决方案:http://jsfiddle.net/victmo/SZV6m/

我正在使用jquery的1.8 on函数:win.on('resize scroll', function(){...

<强>的Javascript

var minWidthToStick = 300;

var nav = $('#nav'); // caching nav
var offset = nav.offset().top; // getting offset
var win = $(window); // caching window

win.on('resize scroll', function(){
    if(
        win.width() >= minWidthToStick && 
        win.scrollTop() >= offset
    ){
        nav.css('position', 'fixed');
    }else{
        nav.css('position', 'relative');
    }
}).resize();

不要忘记将该代码放在$(document).ready(function(){ ... })函数中:)