Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

javascript - Function to be called once div hits top of viewport window

Wondering if you could have a look at the below code.

Im wanting a function to be called once the top of the red box hits the top of the viewport on scroll.

JS Fiddle: 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")}
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check this fiddle.

I have added code to alert whenever .test div reaches at top (multiple times). If you need to call the alert/some code only once then you need to remove else part.

Below is the code.

$(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;

  });
});

Hope this is what you are trying to achieve.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...