Fixed page header overlaps in-page anchors

前端 未结 30 3551
逝去的感伤
逝去的感伤 2020-11-22 00:25

If I have a non-scrolling header in an HTML page, fixed to the top, having a defined height:

Is there a way to use the URL anchor (the #fragment part) t

30条回答
  •  半阙折子戏
    2020-11-22 00:58

    I'm using @Jpsy's answer, but for performance reasons I'm only setting the timer if the hash is present in the URL.

    $(function() {
          // Only set the timer if you have a hash
          if(window.location.hash) {
            setTimeout(delayedFragmentTargetOffset, 500);
          }
      });
    
    function delayedFragmentTargetOffset(){
          var offset = $(':target').offset();
          if(offset){
              var scrollto = offset.top - 80; // minus fixed header height
              $('html, body').animate({scrollTop:scrollto}, 0);
              $(':target').highlight();
          }
      };
    

提交回复
热议问题