幽灵 DOM 元素的导航栏固定在顶部无法保持位置

4
我正在使用Bootstrap 3,我有一个全屏幕的轮播图,紧接着是导航栏。当用户完全滚过轮播图后,导航栏会固定在顶部,这很好用。
但是现在,当用户稍微向下滚动一点,然后向上滚动时,导航栏不会回到原来的位置,它仍然固定在顶部。
以下是我的js代码:

$(function() {
  var lastfixed = undefined,
    spacerEl = undefined,
    fixed = false,
    ghostElHeight = 0;

  $(document).on('scroll', function() {
    console.log('scroll top : ' + $(window).scrollTop());

    if ($(window).scrollTop() >= $(".carousel").outerHeight()) {
      fixed = true;
      if (fixed === lastfixed) return
      $(".navbar").addClass("navbar-fixed-top");
      ghostElHeight = $(".navbar").outerHeight()
      if (!!!spacerEl) {
        spacerEl = $(".navbar").after(
          '<div class="navspacer" style="height:' + ghostElHeight + 'px">&nbsp;</div>').next();
      }
    }

    if ($(window).scrollTop() < $(".carousel").height() + ghostElHeight) {
      fixed = false;
      if (fixed === lastfixed) return
      ghostElHeight = 0;
      $(".navbar").removeClass("navbar-fixed-top");
      !!spacerEl && spacerEl.remove();
      spacerEl = undefined;
    }

    lastfixed = fixed;

  });
});

我还创建了一个示例: http://jsfiddle.net/thqx9g9b/2/,以重现此问题。您可能需要点击滚轮,使导航栏固定在顶部,然后向下滚动一点,再向上滚动,才能重现此错误。
奇怪的是,我正在使用全屏jumbtron 进行相同的操作,但该bug并未出现。
更新:如果在.carousel类中添加“padding:55px”,则问题将消失。但是,如果我在carousel中使用图像,则会导致大边框。
以下是带有填充的已更新的fiddle:http://jsfiddle.net/thqx9g9b/3/ 这个问题在我的jumbotron版本中可行的原因是图像设置在父div上,并且填充没有引起边框问题。我尝试在carousel中的各种元素上放置填充,但要使其正常工作,必须放在父div上。是否有任何解决方法或我遗漏了什么?
1个回答

1
你的算法目前似乎有点问题。
现在,如果你向下滚动的距离仅略低于$(".carousel").outerHeight()
-> fixed不会变为true,因此导航栏永远不会失去navbar-fixed-top类。
你需要更改这个。
if ($(window).scrollTop() < $(".carousel").height() + ghostElHeight) {

if ($(window).scrollTop() < $(".carousel").height()) {

然后它会按预期工作。当然,你不必再去处理ghostElHeight。只需在HTML中添加navspacer并使用show/hide切换即可。

另一个问题:

你引入了一个变量lastfixed,使代码变得复杂。 更好的方法是不使用lastfixed

将你的算法从以下方式改变:

fixed = true;
if (fixed === lastfixed) return

if (fixed == true) return
fixed = true;

对于false-part同样适用。这更容易且更清晰。

完整的JS代码:

$(function () {
    var fixed = false;

    $(document).on( 'scroll', function(){

        if($(window).scrollTop()>=$(".carousel").outerHeight())
        {
             if (fixed == true) return
             fixed = true;
             $(".navbar").addClass("navbar-fixed-top");
             $(".navspacer").show();
        }

        if($(window).scrollTop()<$(".carousel").height())
        {
             if (fixed == false) return
             fixed = false;
             $(".navbar").removeClass("navbar-fixed-top");
             $(".navspacer").hide();
        }
    });
});

在导航栏后手动添加navspacer:
<div style="height:100px; display: none;" class="navspacer">&nbsp;</div>

DEMO

可以翻译为:

{{链接1:演示}}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接