一旦上一个兄弟的底部滚动到顶部,我正试图从元素中删除一个类。我要删除的类给元素一个固定的位置,但是一旦用户滚动到固定元素的顶部等于前一个元素的底部的点,我想删除该固定位置。
问题是所有.panel-grid元素都在滚动时丢失了.stuck-section类。
到目前为止,这是我一直没有运气的尝试:
$(window).scroll(function(){
$('.panel-grid.stuck-section').each(function(){
var previous = $(this).prev('.panel-grid');
if ($(this).offset().top <= previous.scrollTop() + previous.outerHeight()){
$(this).removeClass('stuck-section');
}
});
});
我试图通过更改
来修复它var previous = $(this).prev('.panel-grid').not('.stuck-section');
没有运气,它仍然会从所有.panel-grid
中删除该类这是一支笔:discussion
任何建议表示赞赏。谢谢!
var panelCount = $('.panel-grid').length;
var num = panelCount;
$(document).ready(function(){
$('.panel-grid').each(function(){
$(this).attr('data-number', num--);
var dataNum = $(this).attr('data-number');
});
$('.panel-grid:not(:first)').addClass('stuck-section');
$('.panel-grid.stuck-section').each(function(){
var dataNum = $(this).attr('data-number');
$(this).css({'bottom': dataNum * 46 - 46, 'z-index': 100 - dataNum });
});
});
$(window).scroll(function(){
$('.panel-grid.stuck-section').each(function(){
var curDataNumber = $(this).attr('data-number');
var previous = $(this).prev('.panel-grid');
if ($(this).offset().top <= previous.scrollTop() + previous.outerHeight()){
$(this).removeClass('stuck-section');
}
});
});
.panel-layout{
width:100%;
padding-bottom: 300px;
}
.panel-grid{
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: nowrap;
-ms-justify-content: space-between;
justify-content: space-between;
background-color:lightgray;
min-height: 1000px;
}
.stuck-section{
width: 100%;
min-height: 46px;
height: 46px;
position: fixed;
left: 0;
box-shadow: 0px -3px 6px rgba(0,0,0,0.3);
}
.large-heading{
width: 100%;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-layout">
<div class="panel-grid">
<p class="large-heading">Section 1</p>
</div><!--panel-grid-->
<div class="panel-grid">
<p class="large-heading">Section 2</p>
</div><!--panel-grid-->
<div class="panel-grid">
<p class="large-heading">Section 3</p>
</div><!--panel-grid-->
<div class="panel-grid">
<p class="large-heading">Section 4</p>
</div><!--pannel-row-->
<div class="panel-grid">
<p class="large-heading">Section 5</p>
</div><!--panel-grid-->
</div><!--panel-layout-->
答案 0 :(得分:0)
我认为滚动高度的计算出了问题。我摆弄了一下,现在似乎工作了。
改变了这个:
var scrollHeight = previous.scrollTop() + previous.outerHeight()
if (scrollHeight >= $(this).offset().top){
到这个
var scrollHeight = previous.offset().top+ previous.outerHeight()
if (scrollHeight < $(this).offset().top){