固定菜单位置在滚动顶部

Fixed menu position top on scroll

菜单是固定的,并且偏离 header 的顶部高度。 但是当我滚动时 header 上升,因为它没有固定。所以菜单也应该向上滚动。

查找演示here

我只希望向下滚动时菜单顶部不应该有偏移边距。

$(window).scroll(function(){
  var y = $(window).scrollTop();
  var bgp = $(window).scrollTop();
  var mtv = $('.menu').position().top;
  if(y > 0){
    $('.menu').css({'top': + mtv-bgp +'px'});  
  } else{
    $('.menu').css({'top': + bgp-mtv+'px'}); 
  }
});

如果我得到你想要的正确结果,那么这应该对你有帮助:

body{
    margin:0;
    padding:0;
}
.header{
    background:#ddd;
    height:80px;
    position:relative;
}
.container{
    height:1000px;
    background:#eee;
    position:relative;
    width:100%;
}
.menu{
    background:#000;
    width:200px;
    height:100%;
    left:0;
    top:80px;
    position:fixed;
    z-index:11;
    transition: all 0.6s ease;
}
#toggle{
    width:50px;
    height:50px;
    background:yellow;
    float:left;
    margin:10px 20px;
}

和 js

   $(window).scroll(function(){
      var y = $('body').scrollTop();
      if(y > 80){
        $('.menu').css({'top':'0px'});  
      } 
        else if(y<80)
            $('.menu').css({'top':'80px'}); 
    });

我也更新了你的小提琴: https://jsfiddle.net/g6wfy740/2/