中间有粘性标题

时间:2017-12-21 16:11:26

标签: jquery html css scroll sticky

我试图在中间区域中制作粘贴标题。当页面滚动到 NFC 元素时,它应该粘在顶部。但是当页面滚动到 <ul id="scroll-list"></ul>

时,它不能粘在顶部

我已经接近了@izulito的解决方案。

问题我在此更新的解决方案中看到,标题元素似乎移动到它的原始位置,我通过验证滚动到 <div id="stop-sticky"></div> 后,console.log($('#header').offset().top);。它使标题div在转换时闪烁。

  

我想要一个平滑的滚动条,其中标题应该消失并随着滚动重新出现。   

&#13;
&#13;
<div id="stop-sticky"></div>
&#13;
$( document ).ready(function() {
	var actualPosition = $('#header').offset().top;
	$(window).scroll(function (event) {
	console.log($('#header').offset().top);
  if($(window).scrollTop() > $('#stop-sticky').offset().top) {
      $('#header').addClass('nonstiky');
    } else {
          $('#header').removeClass('nonstiky');}
	});
});
&#13;
#summary {
		  width: 100%;
		  height: 300px;
		  background: #ccc;
		}

		#header {
		  width: 100%;
		  height: 60px;
		  background: #fcc;
		  position: sticky;
		  top: 10px;
		}
    
    #header.nonstiky {
      position: relative
      }

		#scroll-list {
		  height: 500px;
		  background: #cc1;
		}
    #stop-sticky {
		  height: 1000px;
		  background: #c01;
		}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

检查此代码。滚动传递stop-sticky id时,我在标题中添加了一个类。

$( document ).ready(function() {
	var actualPosition = $('#header').offset().top;
	$(window).scroll(function (event) {
  if($(window).scrollTop() > $('#stop-sticky').offset().top) {
      $('#header').addClass('nonstiky');
    } else {
          $('#header').removeClass('nonstiky');}
	});
});
#summary {
		  width: 100%;
		  height: 300px;
		  background: #ccc;
		}

		#header {
		  width: 100%;
		  height: 60px;
		  background: #fcc;
		  position: sticky;
		  top: 10px;
		}
    
    #header.nonstiky {
      position: relative
      }

		#scroll-list {
		  height: 500px;
		  background: #cc1;
		}
    #stop-sticky {
		  height: 1000px;
		  background: #c01;
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
	<div id="summary">Summary</div>
	<div id="header">Header</div>
	<ul id="scroll-list"></ul>
        <div id="stop-sticky"></div>
</body>