修正了当位置动态给定时导航条覆盖内容的问题

fixed navigation bar overlaying content when position is given dynamically

本文关键字:覆盖 问题 导航 定时 位置 动态      更新时间:2023-09-26

我正在尝试创建一个有多个部分的单页网站。我的问题是,一旦我点击导航栏中的链接,它就会滚动到该项目,但只覆盖了部分内容。

导航只在滚动超过其原始位置时给出静态定位(希望这有意义)。这是一个链接到我的开发网站http://wp.matthewwood.me/

下面是我使用JQuery添加固定定位的代码。我试着用-50px来偏移它以适应固定的导航大小,但这并没有解决问题。

   $(document).ready(function(){
   var offset = $(".navbar").offset().top;     
   $(window).scroll(function() {
         if ($(window).scrollTop() >= offset) {
             $('.navbar').addClass('navbar-fixed-top');
         }
         else {
             $('.navbar').removeClass('navbar-fixed-top');
         }
    });
$('a.page-scroll').bind('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({scrollTop: $($anchor.attr('href')).offset().top - 50}, 1500, 'easeInOutExpo');
    event.preventDefault();
});
});

如有任何帮助,不胜感激

当您从相对位置更改为固定位置时,div的块值从其高度更改为零。这会导致您遇到的偏移问题。看这把小提琴:https://jsfiddle.net/7muk9zhh/5/

主要变化:

JS:

$(window).scroll(function() {
    if ($(window).scrollTop() >= offset) {
        $('.navbar').addClass('navbar-fixed-top');
        $("#Main").css("margin-top", $(".navbar").height()); //Compensates for fixed positioning
    } else {
        $('.navbar').removeClass('navbar-fixed-top');
        $("#Main").css("margin-top", "");
    }
});
$('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        var globOffset = $(".navbar").height(); //Acts as an offset for the fixed element
        $('body').stop().animate({scrollTop: $($anchor).attr('href').offset().top - globOffset}, 1500);
        event.preventDefault();
    });

HTML:

还有一个问题。"#home"锚在body中使用。因此,当找到this的偏移顶部时,它返回0 (body元素的偏移量)。

我还认为自定义舒缓'easeInOutExpo'需要jQuery UI(如果这不起作用,你需要包括它):

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

希望这能回答你的问题!

使用这段代码:应该可以正常工作,并有很好的平滑滚动效果:

   $(document).ready(function(){
   var offset = $(".navbar").offset().top;     
   $(window).scroll(function() {
         if ($(window).scrollTop() >= offset) {
             $('.navbar').addClass('navbar-fixed-top');
         }
         else {
             $('.navbar').removeClass('navbar-fixed-top');
         }
    });
 //here it starts
   $('a[href^="#"]').bind('click.smoothscroll',function (e) {
       e.preventDefault();
       var target = this.hash,
           $target = $(target);
       $('html, body').stop().animate({
           'scrollTop': $target.offset().top-90 //change value to your need 
       }, 1200, 'swing', function () {
           window.location.hash = target;
       });
   });
  //end
  });