固定粘头跳转后onscroll事件

Fixed sticky header jumps after onscroll event

本文关键字:onscroll 事件      更新时间:2023-09-26

我有一个粘头下面的代码,但我不能使滚动平滑过渡。固定页眉在单次滚动后跳转。

基本html:
<div class="headerWrapper">
    <div id="top-nav-wrapper"></div>
        <div class="header"></div>
</div>
   <div class="headerPlaceholder"></div>
        <div class="mainContent">
          *page content goes here*
         </div>
CSS:

    body {
      background: #EEE;
    }
    #top-nav-wrapper {
      width: 100%;
      position: relative;
      box-shadow: 0px 1px 1px 0px #B8B8B8;
      z-index: 2001;
      background: #EEE;
    }
    .header {
      position: relative;
      left: 0;
      top: 0;
      width: 100%;
      min-height: 90px;
      z-index: 2000;
      background: #EEE;
      height: 90px;
      box-shadow: 0px 1px 2px #C4C4C4;
    }
.headerPlaceholder {
    height:90px;
    width:100%;
    display:none;
}

body.fixed .header {
    position: fixed;
    top: 0;
}
body.fixed .headerPlaceholder {
    display: block;
}

脚本:

<script>
$(document).ready(function () {
    var start = $('.header').offset().top;
    $.event.add(window, "scroll", function () {
        var p = $(window).scrollTop();
        if( p > start ) {
            $('body').addClass('fixed');
        } else {
            $('body').removeClass('fixed');
        }
    });
});
</script>

为了使它平稳过渡,可能需要稍微延迟和淡出效果,如果有人可以帮助或建议一个替代方案。

这是要测试

的页面

JS小提琴

使用jQuery animate()方法实现更平滑的过渡。使用它,根据您的需要动画div