请您查看This Demo并告诉我为什么当#c
的顶部触及屏幕底部时我无法登录日志?
$(window).scroll(function() {
var elemTop = $("#c").offset().top;
var screenBot = $(window).height();
var currentTop = elemTop - $(window).scrollTop();
if(currentTop == screenBot) {
console.log('Bottom of C Hits the View');
}
});

div{ height:500px; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">Section A</div>
<div id="b">Section B</div>
<div id="c">Section C</div>
<div id="d">Section D</div>
&#13;
答案 0 :(得分:1)
这是因为视图的滚动速度比回调快。如果你慢慢滚动它可以工作
您需要做的是设置一个lastAt
变量,然后测试c部分介于lastAt
和currentTop
var lastAt = 0
$(window).scroll(function() {
var elemTop = $("#c").offset().top;
var scrollTop = $(window).scrollTop();
//console.log(elemTop, scrollTop, lastAt)
// NOTE: this logic only works when scrolling down
// you'll need to extend this logic for scrolling up
if( lastAt < elemTop // havent't hit the c section...
&& scrollTop >= elemTop){ // but we have now
console.log('Section C in View');
}
lastAt = scrollTop
});
div{ height:500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">Section A</div>
<div id="b">Section B</div>
<div id="c">Section C</div>
<div id="d">Section D</div>
注意:当“c部分”的顶部点击屏幕顶部时,会触发此逻辑。
答案 1 :(得分:1)
以下是如何执行此操作的方法。您可以检查window.scrollTop + window.height
是否大于元素的offsetTop
。
$(window).scroll(function() {
var elemTop = $("#c").offset().top;
var screenBot = $(window).height();
if (($(window).scrollTop() + screenBot) > elemTop) {
$('.result').text('Bottom of C Hits the View')
} else {
$('.result').text('')
}
});
&#13;
div {
height: 700px;
}
.result {
position: fixed;
right: 0;
top: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a">Section A</div>
<div id="b">Section B</div>
<div id="c">Section C</div>
<div id="d">Section D</div>
<div class="result"></div>
&#13;