我的目标:
在具有多个div.inView
且默认情况下为隐藏的页面上。当div的任何部分位于视口中时,无论是加载还是滚动到它们中,我都希望它们动画和取消隐藏。
我的代码:
jQuery(document).ready(function($) {
// Check if page has .inView
if ( $('.inView')[0] ) {
// Get viewport
var wt = $(window).scrollTop();
var wb = $(window).scrollTop() + $(window).innerHeight();
// If true, unhide by removing class
function checkVis(e) {
console.log('> > checking');
var et = e.offset().top;
var eb = e.offset().top + e.outerHeight();
// Check if top or bottom are within viewport, or if top and bottom are bigger than viewport
if ( ( (wt < et) &&
(wb > et) ) ||
( (wt < eb) &&
(wb > eb) ) ||
( (wt < et) &&
(wb > eb) ) ) {
console.log('> > > removing');
e.removeClass('preanimated');
}
}
// Initial check to unhide any .inView that are already in viewport
$('.preanimated').each(function() {
console.log('each');
checkVis( $(this) );
});
// Check again if scrolling causes any .inView to pass the test
$(window).scroll(function() {
console.log('> scrolling');
$('.preanimated').each(function() {
console.log('each again');
checkVis( $(this) );
});
});
}
});
结果:
仅checkVis()
的初始运行有效。即使后面的.scroll
可以工作,并且会进入checkVis()
,它也不会触发console.log('> > > removing');
再次删除该类。
答案 0 :(得分:1)
您必须将wt和wb放在checkVis函数中。然后计算应该按预期进行