div一旦命中视口窗口顶部就被调用的函数

时间:2017-05-23 12:27:11

标签: javascript jquery html css

想知道您是否可以查看以下代码。

我想要在红色框的顶部在滚动时击中视口的顶部时调用函数。

JS小提琴:http://jsfiddle.net/ay5ttmLk/

HTML
<div class="test" style="height:100px;width:70px;">
sadfsadf
saf
sadf
saf
s
af
saf
saf
sadf
sadfsafsafsaf
</div>


<div class="test" style="height:100px;width:70px;">
sadfsadf
saf
sadf
saf
s
af
saf
saf
sadf
sadfsafsafsaf
sadfsaf
sadfsafsadf
</div>

CSS
.test {margin-top: 500px;
margin-bottom: 1000px;
background-color: red;}

JS
var el = $('.test');
el.on('scroll', function(){
if(el.scrollTop() == 0){alert("hit the top")}
});

2 个答案:

答案 0 :(得分:0)

我认为没有办法检查顶部视口(文档顶部)。但是,您可以进行手动测试来检查它:

$(window).on('scroll', function() { 
    var topViewPort = $(window).scrollTop();
    // You have 2 problems here
    // - Your el is an array with two elements. You have to specify which one you want to check or add extra condition
    // - scrollTop on the element doesn't mean anything. You need to use offset().top to get the data
    var topElement = $(".test").eq(0).offset().top; 

    // Do small check (gap length < 100?) to consider it on top.
}

答案 1 :(得分:0)

检查this fiddle

我添加了代码,以便在.test div到达顶部(多次)时发出警报。如果您只需要调用一次警报/某些代码,那么您需要删除其他部分。

以下是代码。

$(document).ready(function() {
  $('.test').attr("attop", false);
  var lastScrollTop = 0;
  $(window).on('scroll', function() {
    var windowScrollTop = $(this).scrollTop();


    if (windowScrollTop > lastScrollTop) {
        var currentDiv = $('.test[attop="false"]:first');
        if (currentDiv && currentDiv.length > 0) {
            if (windowScrollTop >= currentDiv.offset().top) {
                currentDiv.attr('attop', true);
                alert('reached top');
            }
        }

    } else {//this part needs to be removed to call only once
        var currentTopDivs = $('.test[attop="true"]');
        if (currentTopDivs && currentTopDivs.length > 0) {
            $.each(currentTopDivs,function(i,elem){
                if (windowScrollTop <= $(elem).offset().top) {
                    $(elem).attr('attop', false);
                }                   
            });
        }
    }
    lastScrollTop = windowScrollTop;

  });
});

希望这是你想要实现的目标。