当用户滚动通过它时,我正在制作一个“粘住”页面顶部的粘性侧边栏。然而,侧边栏并不像它应该的那样工作,它总是在静态和固定位置之间来回切换,就像用户滚动一样。
$(document).scroll(function () {
var docScroll = $(this).scrollTop();
var stickyListOffset = $(".sticky-list").offset().top;
if(docScroll > stickyListOffset){
$(".sticky-list").css({
'position' : 'fixed',
'top' : '0px',
'width' : '100%'
});
} else {
$(".sticky-list").css({
'position' : 'static'
})
}
}); CSS:
.sticky-list {
background:#7C9ED9;
padding:1em;
list-style:none;
font-family:Domine, serif;
}
.sticky-list #indicator {
font-size:.8em;
color:#fff;
font-style:italic;
font-family:Bitter, serif;
}
.sticky-list #indicator:after {
width:100%;
content:"";
display:block;
background:#fff;
height:2px;
}HTML:
<ul id="jump-list" class="sticky-list">
<span id="indicator">Jump To...</span>
<li><a href="#open-console">Opening the Console</a></li>
<li><a href="#writing-to-console">Writing to the Console</a></li>
</ul> 然而,跳杆闪烁之间的静态和固定的定位,而不是它应该如何。为什么这不管用?
页面
发布于 2015-11-03 20:11:23
当您将位置设置为fixed时,粘性列表的offset().top将更改为$(this).scrollTop + 10,这是因为粘性列表的"top: 10"样式。变化
if(docScroll > stickyListOffset){ 至
if(docScroll + 10 >= stickyListOffset){ 它应该能起作用
发布于 2016-08-04 11:17:04
当您滚动时,.offset().top值正在发生变化,这就是它闪烁的原因。您需要在.offset().top之前计算scroll function
我建议您不要在jQuery中使用css,因为它添加了内联css,这并不是件好事。相反,在css中添加类的粘性和样式。这将是最干净的方式来做到这一点。
如果您希望列表通过后变得粘稠,也可以计算.outherHeight() + .offset().top。
.outherHeight(),因为ul有一个padding:1em,仅仅使用.height()并不考虑填充。
我计算了什么时候列表应该是粘性的,有一些变量可以更清楚地显示。
见片段
var stickyHeight = $(".sticky-list").outerHeight(),
stickyListOffset = $(".sticky-list").offset().top,
whenToSticky = stickyHeight + stickyListOffset
$(document).scroll(function () {
var docScroll = $(this).scrollTop();
if(docScroll > whenToSticky ){
$(".sticky-list").addClass("sticky")
} else {
$(".sticky-list").removeClass("sticky")
}
}); .sticky-list {
background:#7C9ED9;
padding:1em;
list-style:none;
font-family:Domine, serif;
}
.sticky-list #indicator {
font-size:.8em;
color:#fff;
font-style:italic;
font-family:Bitter, serif;
}
.sticky-list #indicator:after {
width:100%;
content:"";
display:block;
background:#fff;
height:2px;
}
.content {
height:800px;
background:red;
}
.sticky-list.sticky {
position: fixed;
top : 0px;
width : 100%;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="jump-list" class="sticky-list">
<span id="indicator">Jump To...</span>
<li><a href="#open-console">Opening the Console</a></li>
<li><a href="#writing-to-console">Writing to the Console</a></li>
</ul>
<div class="content">
</div>
如果有帮助请告诉我
https://stackoverflow.com/questions/33507804
复制相似问题