为什么固定块在滚动时闪烁?

时间:2017-04-26 18:43:03

标签: javascript jquery html css

我需要在底部创建标题,并在用户滚动时将其固定在顶部。

为什么滚动固定标题时闪烁?

它的代码:



$(document).scroll(function () {
	var bodyTop = $('body').scrollTop();
	var navOffset = $('.main-nav').offset().top;
	$('.main-nav').toggleClass('header-fixed', (bodyTop > navOffset));
});

.wrapper { height: 99000px; }
.header-fixed { 
      position: fixed !important; top: 0 !important; 
      bottom: none; background: yellow !important; }
 .main-nav { width: 100%; height: 72px; position: absolute; bottom:0; background: blue;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <nav class="main-nav">
    </nav>
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/u3kk219d/

1 个答案:

答案 0 :(得分:2)

我已经移动了元素的offsetTop OUTSIDE滚动的计算,它只需要计算一次。通过这样做,每次滚动时都不会弄乱奇怪的计算,并且它会修复闪烁。

var navOffset = $('.main-nav').offset().top;

$(document).on("scroll", function() {
  var bodyTop = $('body').scrollTop();
  $(".main-nav").toggleClass("header-fixed", (bodyTop > navOffset));
});
.wrapper {
  height: 99000px;
}

.header-fixed {
  position: fixed !important;
  top: 0 !important;
  background: yellow !important;
}

.main-nav {
  width: 100%;
  height: 72px;
  position: absolute;
  bottom: 0;
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <nav class="main-nav">
  </nav>
</div>