我正在尝试在中间区域 中制作一个粘性 header 。当页面滚动到 <ul id="scroll-list"></ul>
时,它应该停留在顶部 元素。但是当页面滚动到 <div id="stop-sticky"></div>
时,它一定不能停留在顶部。
我已经接近于遵循@izulito 的解决方案。
但是问题我在这个更新的解决方案中看到的是标题元素似乎移动到它的原始位置,我通过console.log($('#header').offset().top);
验证了这一点, 滚动到 <div id="stop-sticky"></div>
后强>。它使标题 div 在转换时闪烁。
I want a smooth scroll in which header should disappear and reappear along with the scroll.
$( 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');} }); });
#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>
最佳答案
检查这段代码。当您滚动传递 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>
关于jquery - 中间的粘性标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47928731/