元素顶部击中屏幕底部时无法触发功能

时间:2017-02-20 17:16:53

标签: javascript jquery

请您查看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;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

这是因为视图的滚动速度比回调快。如果你慢慢滚动它可以工作

您需要做的是设置一个lastAt变量,然后测试c部分介于lastAtcurrentTop

之间的时间

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

&#13;
&#13;
$(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;
&#13;
&#13;