每次项目滚动到视口时触发事件 [英] Trigger an event each time an item scrolls into viewport
问题描述
我在页面上有一些项目。当他们滚动到视图中时,我向他们添加动画类,如下所示:
I have some items on a page. When they scroll into view, I add animation classes to them, like this:
$(window).scroll(function() {
var topOfWindow = $(window).scrollTop(),
bottomOfWindow = topOfWindow + $(window).height();
$('.buckle').each(function(){
var imagePos = $(this).offset().top;
if (imagePos < topOfWindow+400) {
$(this).addClass('animate');
}
});
});
这会触发动画每页加载一次:当图像距视口顶部400px时,类被添加,动画滚动,然后图像保持静态。
This triggers the animation to occur one time per page load: when the image is 400px from the top of the viewport, the class gets added, the animation rolls, then the image remains static.
但现在无论用户是向上还是向下滚动,它们都会在每次滚动到视口时进行动画处理。在演示的情况下,滚动元素在滚出视图后会丢失类.animate,并在滚动回到视图时重新应用。
But now they are meant to animate once each time they scroll into the viewport, whether the user is scrolling upwards or downwards. In the case of the demo, the "Buckle" element would lose the class .animate after scrolling out of view, and have it re-applied when scrolling back in to view.
使用JQuery触发这个的最有效方法是什么?
What would be the most efficient approach for triggering this with JQuery?
推荐答案
我不确定我是否完全理解你,但我认为从顶部触发动画 400px
并不是一个好主意。如果窗口/视口的高度甚至小于 400px
,动画将在滚动到视图之前启动。我认为应该通过Windows底部确定。
I'm not sure if I entirely understood you, but I think its not a very good idea to trigger the animation 400px
from the top. What if the window/viewport's height is even less than 400px
, the animation would be initiated before it was scrolled into view. I think it should be determined via the windows bottom.
$(window).scroll(function () {
var topOfWindow = $(window).scrollTop(),
bottomOfWindow = topOfWindow + $(window).height();
$('.buckle').each(function () {
var imagePos = $(this).offset().top;
if(imagePos <= bottomOfWindow && imagePos >= topOfWindow){
$(this).addClass('animate');
}else{
$(this).removeClass('animate');
}
});
});
以下是演示: http://jsfiddle.net/2LPmr/1/
干杯!
这篇关于每次项目滚动到视口时触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!