在加载页面上,存储每个 div 的顶部位置、底部位置和类名:
positions = {}
for $div in $('div')
topPosition = $div.offset().top
bottomPosition = topPosition + $div.outerHeight()
positions[topPosition] = positions[bottomPosition] = $div.attr('class')
存储顶部和底部位置允许在div
从下方输入 a 时得到通知。
位置对象将只计算一次,看起来像:
{
0: 'splash-screen',
400: 'splash-screen',
401: 'about-us',
801: 'about-us',
802: 'contact-us',
1202: 'contact-us'
}
然后监听窗口滚动事件并调用:
$(window).scroll ->
return unless divClassName = positions[window.scrollY]
console.log "Entering #{divClassName}!"
在 JavaScript 中编辑:
var positions = {};
$('div').each(function(index) {
var topPosition, bottomPosition;
topPosition = $(this).offset().top;
bottomPosition = topPosition + $(this).outerHeight();
positions[topPosition] = positions[bottomPosition] = $(this).attr('class');
})
$(window).scroll(function(e){
if (positions[window.scrollY] == undefined) return;
console.log('Entering ' + positions[window.scrollY] + '!');
})