滚动时固定在页面顶部的菜单栏会导致下面的内容在滚动过程中跳转

Menu bar fixed at top of the page when scrolling is causing content underneath to jump during scroll

本文关键字:滚动 过程中 菜单栏 顶部      更新时间:2023-09-26

我试图让子菜单在滚动时滚动时停留在页面顶部,一旦它在滚动过程中到达顶部。这是我到目前为止所拥有的:

$(window).scroll(function () {    
  if ($(window).scrollTop() > 175) {
$('#location_menu').css('position', 'fixed').css('top','0px').css('z-index','1000');
$('.first').css('padding-top','415');}
  else { 
$('#location_menu').css('position', 'relative').css('z-index','1');
 }});

我遇到的问题是滚动不流畅,一旦元素从位置:相对更改为位置:固定,内容似乎跳跃/跳过大约 415px,与子菜单的高度相同。

这是 css:

 <div id="location_menu" >submenu content
 </div>
 <div id="content" class="location_detail first">content beneath submenu
 </div>

我已经为.first添加了行,当页面滚动并达到页面顶部的 175px 以内时,具有 415px 的填充顶部.css('padding-top','415')但这实际上似乎并没有做任何事情。没有变化,所以我假设我执行错误了。

我应该使用上面列出的其他滚动功能吗?





这是我最终用来解决我的问题的方法,基于 @Danko 中的代码:

$(window).scroll(function () {
  var $conten = $('.first'),
      $menu = $('#location_menu')
      scrollpos = $(window).scrollTop();
  if (scrollpos >= 175) {
      $conten.css('padding-top','365px');
      $menu.css('position', 'fixed').css('top','0px').css('z-index','1000');
  } else {
      $conten.css('padding-top','0');
      $menu.css('position', 'fixed').css('position', 'relative').css('z-index','1');
  }
});

Edit

好的,现在我明白了这个问题,我 http://codepen.io/anon/pen/BdkLf 做了这个演示。

功能实际上是这样的:

$(window).scroll(function () {
  var $menu = $('#location_menu'),
      $conten = $('#content'),
      scrollpos = $(window).scrollTop();
  if (scrollpos >= 175) {
      $menu.css( {
        "top" : "0",
        "position": "fixed",
      });
      $conten.css('top','375px' );
  } else {
      $menu.css( {
        "position": "relative",
        "top" : "175px",
      });
      $conten.css('top','175px');
  }
});

这里的175等于与顶部的初始距离,375是距离和菜单height之间的相加