我在使用jQuery创建粘性 header 方面有一个特定的问题。我在网络上尝试了常用的代码段,但是到处都感觉到同样的错误。

在特定的文档高度(可滚动直到比调用粘滞效应稍高一点)时,粘滞头在position: fixedposition: static之间跳转。

HTML:

<header>
  <div id="not-sticky"></div>
  <div id="sticky"></div>
</header>
<div id="content"> ...

jQuery:

var $sticky = $("#sticky");
var offset = $sticky.offset();
var stickyTop = offset.top;
var windowTop = $(window).scrollTop();
$(window).scroll(function() {
  windowTop = $(window).scrollTop();
  if (windowTop > stickyTop) {
    $sticky.css({
      position: 'fixed',
      top: 0
    });
  }
  else {
    $sticky.css({
      position: '',
      top: ''
    });
  }
});

CSS:

header {
  width: 100%;
}

#not-sticky {
  padding: 50px 0;
  width: 100%;
}

#sticky {
  padding: 24px 0;
  position: relative;
  width: 100%;
  z-index: 25;
}

我还尝试在#not-sticky上设置一个与#sticky相同的高度的边距底边,以保持恒定的文档高度,但是发生了同样的跳动粘滞效应。

有解决这个问题的主意吗?

最佳答案

滚动会触发太多次,尝试设置元素style总是&不可避免地会产生跳转(即使几乎没有引起注意,但仍然很锯齿)。

我发现最好的方法是

  • 复制我们的元素
  • 使该克隆fixed
  • 以克隆的visibility样式播放。

  • 纯JS:

    ;(function(){ /* STICKY */
    
      var sticky  = document.getElementById("sticky"),
          sticky2 = sticky.cloneNode(true);
    
      sticky2.style.position = "fixed";
      document.body.appendChild(sticky2);
    
      function stickIt(){
        sticky2.style.visibility = sticky.getBoundingClientRect().top<0 ? "visible" : "hidden";
      }
    
      stickIt();
      window.addEventListener("scroll", stickIt, false );
    }());
    #sticky{
      height:100px;
      background:#ada;
      height:50px;
      position:relative;
      /* needed for clone: */
      top:0;
      width:100%;
    }
    
    
    /* Just for this demo: */
    *{margin:0;padding:0;}
    #content{height:2000px; border:3px dashed #444;}
    h1{padding:40px; background:#888;}
    <h1>Logo</h1>
    <div id="sticky">Sticky header</div>
    <div id="content">Lorem ipsum...<br>bla bla</div>


    因此,当您看到“ header ”修复程序时,实际上是我们固定的克隆在顶部可见。

    关于javascript - 粘性 header - buggy 在滚动上跳跃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16513794/

    10-14 17:59
    查看更多