繁体   English   中英

固定导航栏,动态定位位置时覆盖内容

[英]fixed navigation bar overlaying content when position is given dynamically

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

仅当滚动超过其原始位置时(导航才有意义),导航才被赋予静态位置。 这是我开发网站的链接http://wp.matthewwood.me/

这是我的使用JQuery添加固定位置的代码。 我尝试将其偏移-50px以适应固定的nav大小,但这尚未解决问题。

   $(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();
});
});

任何帮助,将不胜感激

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

   $(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
  });

当您从相对位置更改为固定位置时,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”锚。 因此,当为此找到偏移顶部时,它返回0(body元素的偏移)。

另外,我认为自定义缓动'easeInOutExpo'需要jQuery UI(如果不起作用,则需要包含它):

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

希望这能回答您的问题!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM