我的页面上有很多部分,所有部分都是全高和全宽。每个部分都包含一个图像。
因此,当访问者向上或向下滚动到当前部分时,该部分上的图像将会显示。如果用户跳过另一部分,则上一节中的图像将会隐藏。
有活生生的例子。像这样; https://cliquestudios.com
假设这些是我的代码。当用户在事件部分时,它应该将“事件”类添加到“文章”标签。当用户离开该部分时,应删除“事件”类并将“事件”类添加到用户的当前部分。
.section .image {
opacity: 0;
}
.section .active .image {
opacity: 1;
}
<section class="all-sections-wrap">
<article class="section">
<div class="image">
<img src="blabla.png">
</div>
</article>
<article class="section">
<div class="image">
<img src="blabla.png">
</div>
</article>
<article class="section">
<div class="image">
<img src="blabla.png">
</div>
</article>
<section>
我在 stackoverflow 中调查了很多主题,但不幸的是我找不到足够好的脚本。这些在检测偏移量和页面高度方面有很多问题。
如果能得到任何帮助,我将不胜感激。
谢谢。
最佳答案
使用 .scroll()
callback在 window
元素上知道页面何时滚动。然后,你可以通过 $(window).scrollTop()
得到页面滚动了多少像素。 .最后,用 $("#element").offset().top
将它与要添加类的元素的偏移量进行比较
$(window).scroll(function(){
if($(window).scrollTop() >= $("#element").offset().top + $("#element").height() || $(window).scrollTop() < $("#element").offset().top)
$('#element').removeClass('active');
else
$('#element').addClass('active');
});
如果您有很多部分,为避免重复上述代码,请使用 each()
.但是要小心,每次调用 scroll()
时测试每个部分可能会对性能产生很大影响。
$(window).scroll(function(){
$('.section').each(function() {
if($(window).scrollTop() >= $(this).offset().top + $(this).height() || $(window).scrollTop() < $(this).offset().top)
$(this).removeClass('active');
else
$(this).addClass('active');
});
});
关于javascript - 根据页面滚动添加/删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49705653/