我在用户滚动后向 div 添加一个类。这工作正常,但由于某种原因,当用户再次向后滚动时,它不会删除此类。控制台中没有错误。我哪里出错了?
var scrolled = $('body').offset().top - 800;
$(window).on('resize scroll', function() {
if ($(window).scrollTop() > scrolled) {
$('#one').addClass('in');
} else {
$('#one').removeClass('in');
}
});
section.bg-red {
background: red;
}
section.bg-blue {
background: blue;
}
section {
min-height: 100vh;
}
section p {
color: red;
text-align: center;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
section.in p {
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="bg-red" id="one">
<p>Well done you scrolled</p>
</section>
<section class="bg-blue">
ddd
</section>
最佳答案
问题是您从主体的偏移顶部减去 800
,这将产生一个负数。窗口的滚动顶部永远不会是负数,因此该类永远不会被删除。
section.bg-red {
background: red;
}
section.bg-blue {
background: blue;
}
section {
min-height: 100vh;
}
section p {
color: red;
text-align: center;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
section.in p {
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="bg-red" id="one">
<p>Well done you scrolled</p>
</section>
<section class="bg-blue">
ddd
</section>
<script>
var scrolled = $('body').offset().top;
$(window).on('resize scroll', function() {
if ($(window).scrollTop() > scrolled) {
$('#one').addClass('in');
} else {
$('#one').removeClass('in');
}
});
</script>
关于javascript - 在滚动上添加和删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51677246/