粘性标题捕捉到顶部到早期

Sticky header snapping to top to early

本文关键字:顶部 标题      更新时间:2023-09-26

我一直在玩这个代码。 我在我的网站上实现了一个粘性导航,一旦用户滚动时标题消失,它就会激活。 标题div 位于导航div 上方。 粘性部分工作正常,但它激活得太快了。一旦我开始滚动,它就会立即捕捉到顶部,然后在标题再次进入视野后不会捕捉到它的原始位置。

这是使其工作的jquery:

(function($) {
  var $body,
    $target,
    targetoffsetTop,
    resizetimer,
    stickyclass = 'sticky'
  function updateCoords() {
    targetoffsetTop = $target.offset().top
  }
  function makesticky() {                     //Sets the sticky class to activate once  
    var scrollTop = $(document).scrollTop()   //the scroll offset is greater than 
    if (scrollTop >= targetoffsetTop) {        //how far the div is from the top.
      if (!$body.hasClass(stickyclass)) {
        $body.addClass(stickyclass)
      }
    } else {                        
      if ($body.hasClass(stickyclass)) {
        $body.removeClass(stickyclass)
      }
    }
  }
  $(window).on('load', function() {
    $body = $(document.body)
    $target = $('#header_lg')              //This is the target div that get's sticky
    updateCoords()
    $(window).on('scroll', function() {
      requestAnimationFrame(makesticky)
    })
    $(window).on('resize', function() {
      clearTimeout(resizetimer)
      resizetimer = setTimeout(function() {
        $body.removeClass(stickyclass)
        updateCoords()
        makesticky()
      }, 50)
    })
  })
})(jQuery)

.CSS:

#header_lg {          //Before sticky
  width: 100%;
  height: 75px;
  padding: .7%;
  background-color: blue;
  -webkit-transition: height 1s, width 1s;
  -moz-transition: height 1s, width 1s;
  transition: height 1s, width 1s;
}
body.sticky #header_lg {   //After sticky
  position: fixed;
  top: 0;
  left: 0;
  height: 100px;
  width: 100%;
}

我对javascript相当陌生,所以专家对代码为什么不能正常工作的任何建议将不胜感激。 如果它很重要,则页面采用引导格式,因此它位于 visible-lg 类中,其中有一个设置为 style="width:100%; margin:0; padding:0;"container类。 HTML 代码只是一个带有一些填充文本的空div。

你没有正确编写你的CSS注释(与js不同):

试试这个:(感谢@Toni在这里我分叉演示的她有用的笔)

#header_lg {          /*Before sticky*/
  width: 100%;
  height: 75px;
  padding: .7%;
  background-color: blue;
  -webkit-transition: height 1s, width 1s;
  -moz-transition: height 1s, width 1s;
  transition: height 1s, width 1s;
}
body.sticky #header_lg {   /*After sticky*/
  position: fixed;
  top: 0;
  left: 0;
  height: 100px;
  width: 100%;
}