jquery固定div向下滚动

时间:2011-04-04 09:12:56

标签: jquery position fixed

我有一个图库导航栏,当页面向下滚动太远时,我希望将其固定在顶部。我的脚本似乎工作正常,但是当应用类时(在相对于固定位置之间转换),存在“跳转”。

Link (根据您的分辨率,您可能需要最小化页面以查看效果)。

代码

<style>  
.HighIndex {z-index: 40; position: fixed; top: 10px;}
</style>

脚本

var msie6 = $.browser == 'msie' && $.browser.version < 7;

    if (!msie6) {
      var top = $('#navContainer').offset().top - parseFloat($('#navContainer').css('margin-top').replace(/auto/, 0));
      $(window).scroll(function (event) {
        // what the y position of the scroll is
        var y = $(this).scrollTop();

        // whether that's below the form
        if (y >= top) {
          // if so, ad the fixed class
          $('#navContainer').addClass('HighIndex');
        } else {
          // otherwise remove it
          $('#navContainer').removeClass('HighIndex');
        }
      });
    } 

2 个答案:

答案 0 :(得分:0)

由于CSS中的top: 10px;,跳跃会产生影响:所有位置都是正确的,但是当应用类时,有10个额外的像素来自任何地方。所以你有两个选择:

1

top: 10px;定义中删除.HighIndex(我想,你不想要)

2

在你的javascript中反映那些10px。这看起来像这样:

if (y >= top - 10) {
      // if so, ad the fixed class
      $('#navContainer').addClass('HighIndex');
} else {
      // otherwise remove it
      $('#navContainer').removeClass('HighIndex');
}

答案 1 :(得分:0)

我创建了一个空的DIV,当导航被抬起时,它会扩展以填充空间。这是代码:

if (!msie6) {
  var top = $('#navContainer').offset().top - parseFloat($('#navContainer').css('margin-top').replace(/auto/, 0));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top-10) {
      // if so, ad the fixed class
      $('#navContainer').addClass('HighIndex');
      $('#navContainerSpacer').css('height','138px');
    } else {
      // otherwise remove it
      $('#navContainer').removeClass('HighIndex');
      $('#navContainerSpacer').css('height','0');
    }
  });
}